ios - 为什么最后调用 DataTaskWithRequest?

标签 ios swift swift2

我必须创建一个应用程序来恢复 API 中的数据,为此我在请求中使用了 NSURLSession.sharedSessiondataTaskWithRequest

我设法恢复了所有信息,但我不明白为什么最后调用 dataTaskWithRequest

func my_connection(login: NSString, password: NSString) -> Void {
let request: NSMutableURLRequest = create_request(login, password: password)
let session = NSURLSession.sharedSession()
print("test1")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
    if (data == nil) {
        NSLog("Error Connection")
    }
    print("test2")
    let res = response as! NSHTTPURLResponse!
    if (my_code_HTTP(res.statusCode) == 0) {
        var jsonData:NSDictionary = NSDictionary()
        do {
            jsonData = try NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
            extract_data_projets(jsonData)
            extract_data_activity(jsonData)
            extract_data_history(jsonData)
            display_board()
        }
        catch {
            NSLog("Error")
        }
        my_connection_user()
        my_connection_notes()
    }
})
print("test3")
task.resume()
print("test4")
}

这是我编译后得到的:

 test1
 test3
 test4
 test2

最佳答案

是因为你在做异步请求。您的请求将在最少执行。在 resume() 之后,但不是紧接着。您在 test3 之后执行 task(),因此这会使您的异步请求持续到最后。如果您在 test3 之前执行此操作,并且如果您的请求非常快,它可能会在 test4 之前完成,但您永远不会知道。

关于ios - 为什么最后调用 DataTaskWithRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33768354/

相关文章:

ios - 如何在 iOS 中创建动态表单?

swift - 可解码 JSONSerialization 错误自定义对象 alamofire

ios - iOS 图表库的问题

xcode - Swift:不同版本的 XCode 给出不同的错误

ios - CoreSpotlight 缩略图图像未显示在 Spotlight 搜索中

iOS:从 iPad 应用程序的物理键盘接收 cmd-B 等键

ios - 通过来自 UITextField 的 Int 可选变量收到 "fatal error: unexpectedly found nil while unwrapping an Optional value"

ios - 撤消模式并同时显示转场

ios - 如何使用文件管理器将 iCloud 中的文件复制到应用程序沙箱

objective-c - 将数组中的数据从一个 View 传输到另一个 View