iOS9 sendSynchronousRequest deprecated

后端 未结 7 1408
自闭症患者
自闭症患者 2020-12-24 13:15

Warning:\'sendSynchronousRequest(_:returningResponse:)\' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSe

7条回答
  •  梦毁少年i
    2020-12-24 13:39

    Swift 4 / Xcode 9

    If you really want the request to be synchronous like in the deprecated semantics, you can block the main thread with an empty loop on a condition set true by the completion handler:

    let request = URLRequest(url: URL(string: "YOUR_URL")!)
    let session = URLSession.shared
    var gotResp = false
    
    let task = session.dataTask(with: request,
                completionHandler: { data, response, error -> Void in
                    // do my thing...
                    gotResp = true
                })
    task.resume()
    
    // block thread until completion handler is called
    while !gotResp {
        // wait
    }
    
    print("Got response in main thread")
    ...
    

    EDIT: or if you prefer to use semaphores like in the Obj-C Nick H247 answer:

    let request = URLRequest(url: URL(string: "YOUR_URL")!)
    let session = URLSession.shared
    let ds = DispatchSemaphore( value: 0 )    
    let task = session.dataTask(with: request,
                completionHandler: { data, response, error -> Void in
                    // do my thing..., then unblock main thread
                    ds.signal()
                })
    task.resume()
    
    // block thread until semaphore is signaled
    ds.wait()
    
    print("Got response in main thread")
    ...
    

提交回复
热议问题