Swift 4的简单网络请求

时间:2019-01-13 22:53:51

标签: swift

我目前正在学习来自Web开发背景的快速知识,我对提出一个简单的网络请求有些困惑。

我正在使用下面的文档来了解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)

1 个答案:

答案 0 :(得分: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