Swift:Swift合并同步

j2cgzkjk  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(143)
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

beq87vna

beq87vna1#

试试看:

import Combine
import PlaygroundSupport
import UIKit

public func example(of: String, execute: () -> Void) {
    print("------ \(of) ------")
    execute()
}

var cancellable: Cancellable?

example(of: "URLSession+Publisher") {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }

    cancellable = 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)")
        })
}

PlaygroundPage.current.needsIndefiniteExecution = true

您需要告诉playground页面在最后一行代码之后继续运行,以便它可以等待服务器响应,并且您需要存储可取消的代码。

相关问题