我用一个文件来处理我的我的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