Swift的iOS API控制器停止工作
我正在使用一个文件来处理我对我的API的调用,如下所示:
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) } }) } }
我使用类似这样的方式来调用它:
var APIBaseUrl: String = "http://***.se/**/**.php" var urlString:String = "\(APIBaseUrl)" self.api.delegate = self api.GetAPIResultsAsync(urlString, elementName:"groupActivities")
这最近工作很好,但现在我的应用程序崩溃,我在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 6.0 GM和Wifi连接的错误。
为了解决这个问题,请尝试这些步骤
- closures你的模拟器
- closures你的Xcode
- 转到您的DerviedData文件夹,并删除它下面的所有文件夹。 (〜/ Library / Developer / Xcode / DerivedData)不用担心在Xcode中打开项目时会再次创build文件夹。