import UIKit
import Combine
public func example(of: String, execute: () -> Void) {
print("------ \(of) ------")
execute()
}
example(of: "URLSession+Publisher") {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }
let _ = URLSession.shared
.dataTaskPublisher(for: url)
.sink(receiveCompletion: { completion in
if case .failure(let error) = completion {
print("Failed with error \(error)")
} else {
print("Success")
}
}, receiveValue: { data, response in
print("Data retrieved with size \(data.count), response = \(response)")
})
}
此代码不打印同步内部的任何内容。我试图通过操场运行它,我的xcode版本是12. 5. 1
1条答案
按热度按时间beq87vna1#
试试看:
您需要告诉playground页面在最后一行代码之后继续运行,以便它可以等待服务器响应,并且您需要存储可取消的代码。