我的代码:
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 PromiseKitimport PMKFoundationlet session = URLSession.sharedfirstly { 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.sharedfirstly { 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行.所以我创建了进行处理的方法.
总结以上是内存溢出为你收集整理的ios – 如何在Swift中优化链接异步请求全部内容,希望文章能够帮你解决ios – 如何在Swift中优化链接异步请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)