【问题标题】:sendSynchronousRequest:returningResponse:error: - What shall I use now? [duplicate]sendSynchronousRequest:returningResponse:error: - 我现在应该使用什么? [复制]
【发布时间】:2026-02-18 17:30:01
【问题描述】:

我现在应该用什么来代替NSURLConnection's

sendSynchronousRequest:returningResponse:error:

在 iOS 9 中?

【问题讨论】:

    标签: swift nsurlconnection ios9


    【解决方案1】:


       sendAsynchronousRequest 在 iOS 9 中已弃用。
       ObjC

     NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
              completionHandler:^(NSData *data,
                                  NSURLResponse *response,
                                  NSError *error) {
                // handle response
    
      }] ]; 
    

    斯威夫特

    let session = NSURLSession.sharedSession()
            session.dataTaskWithRequest(request) { (data, response, error) -> Void in
        }
    

    您必须创建一个 NSMutableURLRequest 对象并指定您的 URL 和 HTTP 方法。

    注意:您还可以创建一个委托类并添加一个 NSURLSessionDataDelegate 协议来接收响应,而不是在 UI 类中添加所有网络代码。
    tutorial1tutorial2

    【讨论】:

      最近更新 更多