【问题标题】:Simple network request with Swift 4使用 Swift 4 的简单网络请求
【发布时间】:2019-01-13 22:53:50
【问题描述】:

我目前正在从 Web 开发背景中学习 swift,但我在提出一个简单的网络请求时有点卡住了。

我正在使用下面的文档来了解URLSessiondataTask,但我似乎对文档如何使用with 存在概念上的误解。 (任何解释将不胜感激)

https://developer.apple.com/documentation/foundation/urlsession/1410330-datatask

这是我的代码:

import Foundation

let url = URL(string: "https://swapi.co/api/people/1/")
let urlSession = URLSession.shared


func completionHandler (_ data : Data?, _ response : URLResponse?, _ error : Error?) -> Void {
    print("Completed.")
}

urlSession.dataTask(with url : url, completionHandler : completionHandler)

错误:

Playground execution failed:

error: MyPlayground.playground:5:26: error: expected ',' separator
urlSession.dataTask(with url : url, completionHandler : completionHandler)
                         ^
                        ,

Xcode 9.2 版

Swift 版本 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2)

【问题讨论】:

    标签: swift


    【解决方案1】:

    试试

    urlSession.dataTask(with: url!, completionHandler: completionHandler)
    

    请注意,您在此处强制解开 url。最好使用guard letif let 来避免它。

    if let url = URL(string: "https://swapi.co/api/people/1/") {
        let urlSession = URLSession.shared
    
        let completionHandler: (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void  = { _,_,_ in
            print("Completed.")
        }
    
        let task = urlSession.dataTask(with: url, completionHandler: completionHandler)
        task.resume()
    }
    

    在游乐场中,您还需要激活无限期执行

    import PlaygroundSupport
    
    import Foundation
    
    if let url = URL(string: "https://swapi.co/api/people/1/") {
        let urlSession = URLSession.shared
    
        let completionHandler: (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void  = { _,_,_ in
            print("Completed.")
        }
    
        let task = urlSession.dataTask(with: url, completionHandler: completionHandler)
        task.resume()
    }
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      相关资源
      最近更新 更多