首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 3-发送make synchronous http请求

Swift 3-发送make synchronous http请求
EN

Stack Overflow用户
提问于 2016-11-09 00:07:09
回答 4查看 23.3K关注 0票数 13

我有以下代码:

代码语言:javascript
复制
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中,所以我不能在这里访问响应状态代码

代码语言:javascript
复制
var httpStatusCode:Int = (httpStatus?.statusCode)!

因为任务在调用Task.Resume()之前不会启动,并且任务是异步的,所以它永远不会工作。

有什么办法可以解决这个问题吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-11-09 00:15:26

总有一种方法可以使用异步模式。

要使函数异步,请添加完成块

代码语言:javascript
复制
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, response, 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", 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)
         }
         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", 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)
      }
      completion(httpStatusCode)
   }
   task.resume()

}

就这样叫它

代码语言:javascript
复制
completeLoadAction(urlString: "www.something.com") { code in
   print(code)
}
票数 10
EN

Stack Overflow用户

发布于 2016-11-09 00:12:51

要使其同步并等待,您可以使用信号量,如下所示

代码语言:javascript
复制
struct Login {

    static func execute() -> Bool {
        let request = NSURLRequest....

        var success = false
        let semaphore = DispatchSemaphore(value: 0)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { _, response, error in
            if let error = error {
                print("Error while trying to re-authenticate the user: \(error)")
            } else if let response = response as? HTTPURLResponse,
                300..<600 ~= response.statusCode {
                    print("Error while trying to re-authenticate the user, statusCode: \(response.statusCode)")
            } else {
                success = true
            }
            semaphore.signal()
        }) 

        task.resume()
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
        return success
    }
}
票数 41
EN

Stack Overflow用户

发布于 2020-10-22 15:04:28

您可以使用DispatchGroup同步网络呼叫。更安全的线程。

代码语言:javascript
复制
        let group = DispatchGroup()
        for i in 0...100 {
          group.enter()
          URLSession.shared.dataTask(with: NSURL(string: "___URL_STRING___")! as URL, completionHandler: { (data, response, error) -> Void in
                defer { group.leave() }
                print("json:\(i)")
          }).resume()
          group.wait()
        }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40491502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档