
func completeLoadAction(urlString:String) -> Int { let url = URL(string:urlString.trimmingCharacters(in: .whitespaces)) let request = URLRequest(url: url!) let task = URLSession.shared.dataTask(with: request) { data,response,error in guard let data = data,error == nil else { // check for fundamental networking error print("error=\(error)") let ac = UIAlertController(Title: "Unable to complete",message: "The load has been added to the completion queue. This will be processed once there is a connection.",preferredStyle: .alert) ac.addAction(UIAlertAction(Title: "OK",style: .default)) self.present(ac,animated: true) return } let httpStatus = response as? httpURLResponse var httpStatusCode:Int = (httpStatus?.statusCode)! let responseString = String(data: data,enCoding: .utf8) print("responseString = \(responseString)") let ac = UIAlertController(Title: "Completed Successfully",message: "The "+coldel+" has been completed successfully",preferredStyle: .alert) ac.addAction(UIAlertAction(Title:"Continue",style: .default,handler: { action in self.performSegue(withIDentifIEr: "segueConfirmedLoad",sender: self) })) self.present(ac,animated: true) } task.resume() return httpStatusCode} 我需要能够调用它并同时检查返回值,因为它是http状态代码,它会让我知道调用是否成功.
问题是因为它在dataTask中我无法访问响应状态代码
var httpStatusCode:Int = (httpStatus?.statusCode)!
因为任务在调用Task.Resume()之前不会启动,并且任务是异步的,所以它永远不会工作.
这有什么办法吗?
解决方法 总有一种方法可以使用异步模式.要使函数异步,请添加完成块
func completeLoadAction(urlString:String,completion: (Int) -> ()) { let url = URL(string:urlString.trimmingCharacters(in: .whitespaces)) let request = URLRequest(url: url!) let task = URLSession.shared.dataTask(with: request) { data,error in guard let data = data,error == nil else { // check for fundamental networking error print("error=\(error)") dispatchQueue.main.async { let ac = UIAlertController(Title: "Unable to complete",animated: true) } completion(0) // or return an error code return } let httpStatus = response as? httpURLResponse var httpStatusCode:Int = (httpStatus?.statusCode)! let responseString = String(data: data,enCoding: .utf8) print("responseString = \(responseString)") dispatchQueue.main.async { let ac = UIAlertController(Title: "Completed Successfully",preferredStyle: .alert) ac.addAction(UIAlertAction(Title:"Continue",sender: self) })) self.present(ac,animated: true) } completion(httpStatusCode) } task.resume()} 并称之为
completeLoadAction(urlString: "www.something.com") { code in print(code)} 总结 以上是内存溢出为你收集整理的ios – Swift 3 – 发送make同步http请求全部内容,希望文章能够帮你解决ios – Swift 3 – 发送make同步http请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)