我在基于Swift 3.0的iOS应用程序中有一个函数,它应该发送HTTP请求,并在从服务器返回值后通过完成块处理它们。但是,我无法在内部重现此崩溃,但对于用户,我看到它不断发生。代码中的行号在下面的代码片段中标有Crashes。有任何调试建议或线索吗?
func sendRequest(_ parameters : NSDictionary?, requestType : String, urlString : String, completionHandler : @escaping (_ succeeded : Bool, _ response : [String : AnyObject]?) -> ()) {
DispatchQueue.global(qos: .background).async {
let request = NSMutableURLRequest(url: URL(string: urlString)!)
request.httpMethod = requestType
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
if let jsonParams = parameters {
do {
request.httpBody = try JSONSerialization.data(withJSONObject: jsonParams, options: .prettyPrinted)
} catch {
self.log.error("Error -> \(error).")
completionHandler(false, nil)
}
}
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if error != nil {
self.log.error("Error -> \(error?.localizedDescription)")
completionHandler(false, nil)
}
do {
// -----> Crashes here - not sure why?
let result = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? [String : AnyObject]
completionHandler(true, result)
} catch {
self.log.error("Error -> \(error).")
completionHandler(false, nil)
}
})
task.resume()
}
}
崩溃线程的堆栈跟踪:
Crashed: NSOperationQueue 0x170033420 :: NSOperation 0x17405fe00 (QOS: DEFAULT)
0 Jarvis 0x1000a6d74 specialized ContextServer.(sendRequest(NSDictionary?, requestType : String, urlString : String, completionHandler : (Bool, [String : AnyObject]?) -> ()) -> ()).(closure #1).(closure #1) (ContextServer.swift:39)
1 Jarvis 0x1000a5e88 ContextServer.(sendRequest(NSDictionary?, requestType : String, urlString : String, completionHandler : (Bool, [String : AnyObject]?) -> ()) -> ()).(closure #1).(closure #1) (ContextServer.swift)
2 CFNetwork 0x19063e618 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 32
3 CFNetwork 0x190655318 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 296
4 Foundation 0x190b017e4 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 16
5 Foundation 0x190a46358 -[NSBlockOperation main] + 96
6 Foundation 0x190a36954 -[__NSOperationInternal _start:] + 620
7 Foundation 0x190b03b90 __NSOQSchedule_f + 228
8 libdispatch.dylib 0x18eec91c0 _dispatch_client_callout + 16
9 libdispatch.dylib 0x18eed7444 _dispatch_queue_serial_drain + 928
10 libdispatch.dylib 0x18eecc9a8 _dispatch_queue_invoke + 652
11 libdispatch.dylib 0x18eed938c _dispatch_root_queue_drain + 572
12 libdispatch.dylib 0x18eed90ec _dispatch_worker_thread3 + 124
13 libsystem_pthread.dylib 0x18f0d12c8 _pthread_wqthread + 1288
14 libsystem_pthread.dylib 0x18f0d0db4 start_wqthread + 4