我用一個文件來處理我的我的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,並沒有做任何最近的更新。
乾杯!
人們在報告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
工作很好,請發表回答。雖然同樣的錯誤顯示在另一行,但我相信這是我的代碼中的其他錯誤,因爲其他API調用工作正常。謝謝一堆! @SamBudda – 2014-09-23 12:52:16
如果這種情況發生在設備上,是否有解決方案? – Kaili 2014-10-17 17:44:32