iOS9 sendSynchronousRequest deprecated

后端 未结 7 1407
自闭症患者
自闭症患者 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 14:02

    If you need to block the current thread (like Mike Keskinov's answer), best to use gdc semaphore instead of doing a [NSThread sleepForTimeInterval:0]. e.g.

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
              completionHandler:^(NSData *data,
                                  NSURLResponse *response,
                                  NSError *error) {
                // handle response
                dispatch_semaphore_signal(semaphore);
    
      }] resume];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    

    and Swift (tested on 5.0):

    let semaphore = DispatchSemaphore(value:0)
    
    URLSession.shared.dataTask(with: serverUrl) { (httpData, response, error) in
        // handle response
        semaphore.signal()
    }.resume()
    
    semaphore.wait()
    

提交回复
热议问题