我想知道是否有一种方法可以实现重连机制与新的Apple框架结合并使用URLSession发布者
- 试图在 WWDC 2019 中找到一些例子
- 尝试玩
waitsForConnectivity
运气不好(它甚至没有在自定义会话中调用委托)
- tried
URLSession.background
但在发布过程中崩溃了。
我也不明白我们如何以这种方式跟踪进度
有人已经尝试过这样做吗?
upd:
这好像是waitsForConnectivity
不管用 https://developer.apple.com/documentation/ios_ipados_release_notes/ios_ipados_13_beta_8_release_notes在 Xcode 11 测试版中
upd2:
Xcode 11 通用汽车 -waitsForConnectivity
正在工作但是ONLY在设备上。使用默认会话,设置标志并实现会话委托。方法task is waiting for connectivity
无论您是否使用带回调的 init 任务,都会被调用。
public class DriverService: NSObject, ObservableObject {
public var decoder = JSONDecoder()
public private(set) var isOnline = CurrentValueSubject<Bool, Never>(true)
private var subs = Set<AnyCancellable>()
private var base: URLComponents
private lazy var session: URLSession = {
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
public init(host: String, port: Int) {
base = URLComponents()
base.scheme = "http"
base.host = host
base.port = port
super.init()
// Simulate online/offline state
//
// let pub = Timer.publish(every: 3.0, on: .current, in: .default)
// pub.sink { _ in
// let rnd = Int.random(in: 0...1)
// self.isOnline.send(rnd == 1)
// }.store(in: &subs)
// pub.connect()
}
public func publisher<T>(for driverRequest: Request<T>) -> AnyPublisher<T, Error> {
var components = base
components.path = driverRequest.path
var request = URLRequest(url: components.url!)
request.httpMethod = driverRequest.method
return Future<(data: Data, response: URLResponse), Error> { (complete) in
let task = self.session.dataTask(with: request) { (data, response, error) in
if let err = error {
complete(.failure(err))
} else {
complete(.success((data!, response!)))
}
self.isOnline.send(true)
}
task.resume()
}
.map({ $0.data })
.decode(type: T.self, decoder: decoder)
.eraseToAnyPublisher()
}
}
extension DriverService: URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
self.isOnline.send(false)
}
}