How do I run Asynchronous callbacks in Playground

前端 未结 8 752
夕颜
夕颜 2020-11-22 11:38

Many Cocoa and CocoaTouch methods have completion callbacks implemented as blocks in Objective-C and Closures in Swift. However, when trying these out in Playground, the co

8条回答
  •  迷失自我
    2020-11-22 12:07

    Swift 4, Xcode 9.0

    import Foundation
    import PlaygroundSupport
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")!
    
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard error == nil else {
            print(error?.localizedDescription ?? "")
            return
        }
    
        if let data = data, let contents = String(data: data, encoding: String.Encoding.utf8) {
            print(contents)
        }
    }
    task.resume()
    

提交回复
热议问题