Swift Combine同步场景无输出:Xcode12.5.1 Playground运行异常
在Xcode 12.5.1 Playground中运行Combine网络请求无输出的解决方案
问题核心在于Playground的默认执行机制:它会在主线程同步代码执行完毕后立刻终止运行。而URLSession.dataTaskPublisher发起的是异步网络请求,请求还未完成、sink闭包还未执行,Playground就已经停止了,因此看不到任何输出。
解决步骤
- 导入
PlaygroundSupport框架,用于控制Playground的执行生命周期 - 设置
PlaygroundPage.current.needsIndefiniteExecution = true,让Playground保持运行直到异步任务完成或手动结束 - 可选:在请求完成的闭包中调用
PlaygroundPage.current.finishExecution(),在任务结束后主动终止Playground,避免无限运行
修改后的完整代码
import UIKit import Combine import PlaygroundSupport public func example(of: String, execute: () -> Void) { print("------ \(of) ------") execute() } // 让Playground保持运行,等待异步任务完成 PlaygroundPage.current.needsIndefiniteExecution = true example(of: "URLSession+Publisher") { guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { // URL无效时主动结束Playground PlaygroundPage.current.finishExecution() return } let cancellable = URLSession.shared .dataTaskPublisher(for: url) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): print("Failed with error \(error)") case .finished: print("Success") } // 请求完成后主动终止Playground PlaygroundPage.current.finishExecution() }, receiveValue: { data, response in print("Data retrieved with size \(data.count), response = \(response)") }) }
内容的提问来源于stack exchange,提问作者user1845926
相关产品推荐
相关产品推荐

