Reputation: 2232
I'm currently learning swift coming from a web development background and I am a little stuck making a simple network request.
I'm using the document below to learn about URLSession
and dataTask
, but I seems a have a conceptual misunderstanding of how the documentation is using with
. (Any explanation there would be appreciated)
https://developer.apple.com/documentation/foundation/urlsession/1410330-datatask
Here is my code:
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)
The error:
Playground execution failed:
error: MyPlayground.playground:5:26: error: expected ',' separator
urlSession.dataTask(with url : url, completionHandler : completionHandler)
^
,
Xcode version 9.2
Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2)
Upvotes: 0
Views: 254
Reputation: 52227
try
urlSession.dataTask(with: url!, completionHandler: completionHandler)
note that you force unwrap url here. better use guard let
or if let
to avoid it.
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()
}
In playgrounds you also need to activate indefinite execution
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
Upvotes: 2