2014-09-23 66 views
2

我用一個文件來處理我的我的API的調用看起來像這樣:斯威夫特的iOS API控制器停止工作

var APIBaseUrl: String = "http://***.se/**/**.php" 
     var urlString:String = "\(APIBaseUrl)" 

     self.api.delegate = self 
     api.GetAPIResultsAsync(urlString, elementName:"groupActivities") 

import UIKit 

protocol APIControllerProtocol { 
    func JSONAPIResults(results: NSArray) 

} 

class APIController: NSObject { 
    var delegate:APIControllerProtocol? 

    func GetAPIResultsAsync(urlString:String, elementName:String) { 

     //The Url that will be called 
     var url = NSURL.URLWithString(urlString) 
     //Create a request 
     var request: NSURLRequest = NSURLRequest(URL: url) 
     //Create a queue to hold the call 
     var queue: NSOperationQueue = NSOperationQueue() 

     // Sending Asynchronous request using NSURLConnection 
     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in 
      var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil 
      //Serialize the JSON result into a dictionary 
      let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary 

      //If there is a result add the data into an array 
      if jsonResult.count>0 && jsonResult["\(elementName)"]?.count > 0 { 

       var results: NSArray = jsonResult["\(elementName)"] as NSArray 
       //Use the completion handler to pass the results 
       self.delegate?.JSONAPIResults(results) 

      } else { 

       println(error) 
      } 
     }) 
    } 
} 

我使用類似於這樣叫它這近來已經很大,但現在我的應用程序崩潰,我得到這個行中的APIController強調:

let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary 

的上我能想到的事情已經改變了,我從移動4G互聯網切換到了我的WiFi。

在日誌中我得到:fatal error: unexpectedly found nil while unwrapping an Optional value

亮點說:Thread 5: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

這不管我打電話是什麼API的出現。我正在運行Xcode 6.0.1,並沒有做任何最近的更新。

乾杯!

+0

人們在報告Xcode 6GM和Wifi連接有問題。關閉Xcode和模擬器,清理DerviedData文件夾,然後重試。 http://stackoverflow.com/questions/25372318/error-domain-nsurlerrordomain-code-1005-the-network-connection-was-lost – 2014-09-23 12:42:55

+0

工作很好,請發表回答。雖然同樣的錯誤顯示在另一行,但我相信這是我的代碼中的其他錯誤,因爲其他API調用工作正常。謝謝一堆! @SamBudda – 2014-09-23 12:52:16

+2

如果這種情況發生在設備上,是否有解決方案? – Kaili 2014-10-17 17:44:32

回答

5

很多人都在報告Xcode 6.0 GM和Wifi連接有問題。

爲了解決這個問題,請嘗試以下步驟

  • 閉上你的模擬器
  • 關閉您的Xcode
  • 轉到您的DerviedData文件夾,刪除所有文件夾在它之下。 (〜/ Library/Developer/Xcode/DerivedData)不用擔心在Xcode中打開項目時會再次創建文件夾。
+0

它沒有工作。多次嘗試過 – Karthik 2014-10-30 05:04:36

+1

同樣,這對我也不起作用。我假設這隻適用於模擬器? @Karthik,你是否在設備上有這個問題,因爲那是我的問題 – MoMo 2015-01-08 16:04:48

+0

@MoMo你能解決嗎? – Nil 2017-09-05 06:11:30