swift 3.0 : task block is not executed

标签 swift xcode8

我是 Swift 新手,有一个问题。我有以下代码块来运行任务。但是,当我从 Xcode 8.2.1 运行时,此任务 block 不会执行。我做错了什么?

// Execute HTTP Request
let task = URLSession.shared.dataTask(with: request as URLRequest) {
 (data, response, error) in

 // Check for error
 if error != nil
 {
 print("error=\(error)")
 return
 }
 // Print out response string
 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
 print("responseString = \(responseString)")


 // Convert server json response to NSDictionary
 do {
 if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {

 // Print out dictionary
 print(convertedJsonIntoDict)

 // Get value by key
 let sessionId = convertedJsonIntoDict["sessionId"] as? String
 print(sessionId!)

 }
 } catch let error as NSError {
 print(error.localizedDescription)
 }

 }
 task.resume()

是否需要completionHandler?我在 main.swift 文件中运行它。

最佳答案

您的程序在任务完成之前就结束了。

我运行它并得到以下输出:

Hello, World!
Program ended with exit code: 0

然后我在 task.resume() 之后添加了这个,只是为了防止程序停止:

while true {    
}

我可以看到它尝试访问我提供的 URL。

关于 swift 3.0 : task block is not executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42404849/

相关文章:

json - 在 Swift 中循环遍历 JSON 数组

swift - 将日期组件(整数)转换为字符串

ios - macOS 和 iOS 目标是否应该共享相同的授权文件?

ios - Xcode 8 GM -- SQLite 错误代码 :6922, 'disk I/O error'

ios - Application Loader 无法读取 Assets.car

ios - 在 ScrollView 中更改 UIView 同时/更新 ScrollView 高度 - Swift 3/Xcode 8

ios - "Navigation bar"的警告帧在运行时会有所不同出现在 Xcode 8 Swift 3 中

swift - 当从 tableviewcontroller 中的核心数据填充单元格行时,我如何跳过显示某些条目?

ios - disableBackgroundDeliveryForType 是否删除对应的 HKObserverQuery?

swift - 使 Swift 协议(protocol)在关联类型上符合 Equatable