📦URLSession.DataTaskPublisher

負責透過 URL 到網路抓資料的 Publisher。

參考資料

將 Data 轉為 Swift 型別

下面的範例示範如何從網路擷取 JSON 資料,然後轉為自己的 Swift 型別: 👉 Processing URL Session Data Task Results with Combine - Convert Incoming Raw Data to Your Types

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
    })

錯誤處理

  • 暫時的錯誤可用 .retry(_:) 處理。

  • 無法排除的錯誤可用 .catch(_:) 與 .replaceError(with:) 處理

Scheduling Operators

分享網路擷取資料

Last updated

Was this helpful?