異步這個函數有一個奇怪的問題:EXC_BAD_INSTRUCTION在使用NSURLConnection的
func retrieveToken() {
var postRequest = NSMutableURLRequest(URL: NSURL(string: "http://example.com"));
postRequest.HTTPMethod = "POST"
var responseData = NSMutableData();
NSURLConnection.sendAsynchronousRequest(postRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
responseData = NSMutableData(data:data);
})
var responseDict:Dictionary<String,AnyObject> = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: nil) as Dictionary;
}
這個功能應該發送POST請求的URL(有效期)接收的令牌。但是,由於某些原因,當我運行此代碼時,我在將postRequest的HTTPMethod設置爲POST的行處得到EXC_BAD_INSTRUCTION。我覺得我忽略了一些非常明顯的東西,但我看不出什麼。哪裏不對?
你是對的,當我將空數據傳遞給NSJSONSerialization時,它崩潰。 sendSynchronousRequest解決方案實際上只是讓我現在可以專注於程序的其他部分,但我不會堅持到最終結果。 – evilgoldfish
這很可能是因爲您試圖強制將其向下轉換爲非可選字典並且它要返回nil。可能你應該使responseDict爲可選:'var responseDict:Dictionary? = ... as?字典' –
ikuramedia
請注意,這目前打破了Playground,我認爲這是與Quicklook有關,但沒有挖得太深。可選項絕對是你需要的。 – ikuramedia