You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:50:26