📦URLSession.DataTaskPublisher
負責透過 URL 到網路抓資料的 Publisher。
參考資料
將 Data 轉為 Swift 型別
import Foundation // URL
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
// consoles
var con = ""
let console = PlaygroundConsole.default // 🐶 PlaygroundConsole
// Post
struct Post: Codable {
let userId: Int
let id : Int
let title : String
let body : String
}
// 🌀 URL extension
let posts: URL = "http://jsonplaceholder.typicode.com/posts"
let cancellable = URLSession.shared
// ⭐️ produces a tuple: (data: Data, response: URLResponse)
.dataTaskPublisher(for: posts)
// ⭐️ use map(_:) to convert contents of tuple to another type.
// ⭐️ use tryMap(_:) to inspect `response` before inspecing `data`,
// throw an error if the response is unacceptable.
.tryMap() { tuple -> Data in
guard
let httpResponse = tuple.response as? HTTPURLResponse,
httpResponse.statusCode == 200
else { throw URLError(.badServerResponse) }
return tuple.data
}
// ⭐️ convert data to their own types
.decode(type: [Post].self, decoder: JSONDecoder())
// ⭐️ receive final results
.sink(receiveCompletion: {
print ("Received completion: \($0).", to: &con); con
}, receiveValue: {
print ("Received posts: \($0.prefix(3)).", to: &con); con
print("posts: ", $0.count); console
})錯誤處理
Scheduling Operators
分享網路擷取資料
Last updated