天天看点

iOS9.0新增网络请求NSURLSession

最近开发遇到了一个这样的问题:Warning:'sendSynchronousRequest(_:returningResponse:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession),即黄色的警告的,这是因为ios9.0更新了原有的解析方式,

我们原来解析数据是这样的:

    NSString * str1 =@"url地址";

    NSURL *url = [NSURLURLWithString:str3];

    NSError* error = nil;

    NSURLRequest* request = [NSURLRequestrequestWithURL:url];

    NSData *data =[NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:&error];

NSLog(@"dic==%@",dic);

但是发现第五行会报上述错误,解决方法就是换新的获取方式,具体方法为:

oc版:

 NSURLSession *session = [NSURLSessionsharedSession];

        [[session dataTaskWithURL:[NSURLURLWithString:str1]

                completionHandler:^(NSData *data,

                                    NSURLResponse *response,

                                    NSError *error) {

                  NSDictionary *dicww = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:&error];

                    NSLog(@"dicww==%@",dicww);

                }] resume];

swift版:

        var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL"))

        var session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"

        var params = ["username":"username","password":"password"] as Dictionary<String, String>

        var err: NSError?

        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options:nil, error: &err)

        request.addValue("application/json", forHTTPHeaderField:"Content-Type")

        request.addValue("application/json", forHTTPHeaderField:"Accept")

        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Voidin

            println("Response: \(response)")})

        task.resume()

打印结果是一样的。

iOS9.0新增网络请求NSURLSession

感觉这个方法比较简便移动,比以前直观多了。