我的代码执行请求链接像A-> B-> C我正在使用URLSession所有请求都按正确的顺序完成并具有预期的行为.但我想知道如何优化这种链接,因为它看起来非常复杂而且不可重复使用.我正在寻找如何以更灵活的方式进行链接的建议.
我的代码:
URLSession.shared.dataTask(with: URLRequest(url: URL(string: "first")!)){ data,res,err in let second = URLRequest(url: URL(string: "second")!) URLSession.shared.dataTask(with: second){ data,err in let third = URLRequest(url: URL(string: "second")!) URLSession.shared.dataTask(with:third){ data,err in }.resume() }.resume() }.resume()
解决方法
正如@Paulw11所说:
PromiseKit PMKFoundation
import PromiseKit import PMKFoundation let session = URLSession.shared firstly { session.dataTask(with: URLRequest(url: URL(string: "first")!)) } .then { data in session.dataTask(with: URLRequest(url: URL(string: "second")!)) } .then { data in session.dataTask(with: URLRequest(url: URL(string: "third")!)) } .then { data -> () in // The data here is the data fro the third URL } .catch { error in // Any error in any step can be handled here }
使用1(且仅1)重试,您可以使用恢复.恢复就像捕获,但预计之前的那个可以重试.但是,这不是一个循环,只执行一次.
func retry(url: URL,on error: Error) -> Promise<Data> { guard error == MyError.retryError else { throw error } // Retry the task if a retry-able error occurred. return session.dataTask(with: URLRequest(url: url)) } let url1 = URL(string: "first")! let url2 = URL(string: "second")! let url3 = URL(string: "third")! let session = URLSession.shared firstly { session.dataTask(with: URLRequest(url: url1)) } .then { data in session.dataTask(with: URLRequest(url: url2)) } .recover { error in retry(url: url2,on: error) } .then { data in session.dataTask(with: URLRequest(url: url3)) } .recover { error in retry(url: url3,on: error) } .then { data -> () in // The data here is the data fro the third URL } .catch { error in // Any error in any step can be handled here }
注意:为了使这项工作不指定返回类型并需要一个return语句,我需要then然后恢复为1行.所以我创建了进行处理的方法.