iOS开发Swift

session dataTask 同步

session dataTask通常是异步取回结果,我们可以通过semaphore把异步变成同步

//创建URL对象
let urlString:String="http://www.hangge.com"
let url = URL(string:urlString)
//创建请求对象
let request = URLRequest(url: url!)
 
// URLSession.shared 重要
let session = URLSession.shared
 
let semaphore = DispatchSemaphore(value: 0)
 
let dataTask = session.dataTask(with: request,
                   completionHandler: {(data, response, error) -> Void in
                    if error != nil{
                        print(error!)
                    }else{
                        let str = String(data: data!, encoding: String.Encoding.utf8)
                        print(str!)
                    }
                     
                    semaphore.signal()
}) as URLSessionTask
 
//使用resume方法启动任务
dataTask.resume()
 
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
print("数据加载完毕!")
//继续执行其他代码.......