11.1~11.4 同步异步下载以及请求参数设置

来源:互联网 发布:淘宝上化妆品是真的吗 编辑:程序博客网 时间:2024/06/05 14:30

11.0. IntroductionNetworking, JSON, XML, and Sharing

NSURLConnection因特网连接和收发数据

NSJSONSerializationJSON 数据的系列化和反系列化

NSXMLParserXML数据的解析

Twitter framework推特分享

NSURLSession管理网页服务连接


11.1. Downloading Asynchronously with NSURLConnection

异步下载


异步下载是创建新线程下载

同步下载则会阻塞当前线程


-(void)testAsynchronousRequest

{

    NSString *urlAsString =@"http://www.apple.com";

   NSURL *url = [NSURLURLWithString:urlAsString];

   NSURLRequest *urlRequest = [NSURLRequestrequestWithURL:url];

    NSOperationQueue *queue = [[NSOperationQueuealloc]init];

    [NSURLConnection

     sendAsynchronousRequest:urlRequest

    queue:queue

    completionHandler:^(NSURLResponse *response,

                        NSData *data,

                        NSError *error) {

        if ([datalength] >0 && error ==nil){

             /* Append the filename to the documents directory */

//             NSURL *filePath =

//             [[self documentsFolderUrl]

//              URLByAppendingPathComponent:@"apple.html"];

            NSString * sfilePath =NSTemporaryDirectory();

             sfilePath = [sfilePathstringByAppendingString:@"apple.html"];

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

            NSURL * filePath = [NSURLfileURLWithPath:sfilePath];

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

             [datawriteToURL:filePathatomically:YES];

             NSLog(@"Successfully saved the file to %@", filePath);

         }

        elseif ([datalength] ==0 &&

                  error ==nil){

             NSLog(@"Nothing was downloaded.");

         }

        elseif (error !=nil){

            NSLog(@"Error happened = %@", error);

         }

     }];

    NSLog(@"send already");

}



打印:

2014-06-24 15:42:51.786 cookbook7[686:a0b] send already

2014-06-24 15:42:51.799 cookbook7[686:360b] sfilePath = /Users/sunward/Library/Application Support/iPhone Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html

2014-06-24 15:42:51.801 cookbook7[686:360b] filePath = file:///Users/sunward/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html

2014-06-24 15:42:51.806 cookbook7[686:360b] Successfully saved the file to file:///Users/sunward/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html



11.2. Handling Timeouts in Asynchronous Connections

设置请求超时


-(void)testAsynchronousRequest

{

    NSString *urlAsString =@"http://www.apple.com";

   NSURL *url = [NSURLURLWithString:urlAsString];

   //这里初始化时设定超时

//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

   NSURLRequest *urlRequest = [NSURLRequestrequestWithURL:url

                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData

                                           timeoutInterval:30.0f];

    NSOperationQueue *queue = [[NSOperationQueuealloc]init];

    [NSURLConnection

     sendAsynchronousRequest:urlRequest

    queue:queue

    completionHandler:^(NSURLResponse *response,

                        NSData *data,

                        NSError *error) {

        if ([datalength] >0 && error ==nil){

             /* Append the filename to the documents directory */

//             NSURL *filePath =

//             [[self documentsFolderUrl]

//              URLByAppendingPathComponent:@"apple.html"];

            NSString * sfilePath =NSTemporaryDirectory();

             sfilePath = [sfilePathstringByAppendingString:@"apple.html"];

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

            NSURL * filePath = [NSURLfileURLWithPath:sfilePath];

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

             [datawriteToURL:filePathatomically:YES];

             NSLog(@"Successfully saved the file to %@", filePath);

         }

        elseif ([datalength] ==0 &&

                  error ==nil){

             NSLog(@"Nothing was downloaded.");

         }

        elseif (error !=nil){

            NSLog(@"Error happened = %@", error);

         }

     }];

    NSLog(@"send already");

}


11.3. Downloading Synchronously with NSURLConnection

同步下载


-(void)testSynchronousRequest

{

    NSString *urlAsString =@"http://www.apple.com";

   NSURL *url = [NSURLURLWithString:urlAsString];

   //这里初始化时设定超时

//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

   NSURLRequest *urlRequest = [NSURLRequestrequestWithURL:url

                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData

                                           timeoutInterval:30.0f];

   NSURLResponse *response =nil;

   NSError *error =nil;

    NSLog(@"will send ");

   NSData * data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];

    

    

   if ([datalength] >0 && error ==nil){

        /* Append the filename to the documents directory */

        //             NSURL *filePath =

        //             [[self documentsFolderUrl]

        //              URLByAppendingPathComponent:@"apple.html"];

       NSString * sfilePath =NSTemporaryDirectory();

        sfilePath = [sfilePathstringByAppendingString:@"apple.html"];

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

       NSURL * filePath = [NSURLfileURLWithPath:sfilePath];

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

        [datawriteToURL:filePathatomically:YES];

        NSLog(@"Successfully saved the file to %@", filePath);

    }

   elseif ([datalength] ==0 &&

             error ==nil){

        NSLog(@"Nothing was downloaded.");

    }

   elseif (error !=nil){

        NSLog(@"Error happened = %@", error);

    }

   NSLog(@"done");

    

}


打印:

2014-06-24 16:01:20.343 cookbook7[769:a0b] will send 

2014-06-24 16:01:48.185 cookbook7[769:a0b] sfilePath = /Users/sunward/Library/Application Support/iPhone Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html

2014-06-24 16:01:48.186 cookbook7[769:a0b] filePath = file:///Users/sunward/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html

2014-06-24 16:01:48.190 cookbook7[769:a0b] Successfully saved the file to file:///Users/sunward/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FD807AB8-0384-428E-8B4F-091A132F2D12/tmp/apple.html

2014-06-24 16:01:48.190 cookbook7[769:a0b] done


顺便看下这个超时

-(void)testSynchronousRequest

{

    NSString *urlAsString =@"http://www.apple.com";

   NSURL *url = [NSURLURLWithString:urlAsString];

   //这里初始化时设定超时

//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

   NSURLRequest *urlRequest = [NSURLRequestrequestWithURL:url

                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData

                                           timeoutInterval:3.0f];

   NSURLResponse *response =nil;

   NSError *error =nil;

    NSLog(@"will send ");

   NSData * data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];

    

    

   if ([datalength] >0 && error ==nil){

        /* Append the filename to the documents directory */

        //             NSURL *filePath =

        //             [[self documentsFolderUrl]

        //              URLByAppendingPathComponent:@"apple.html"];

       NSString * sfilePath =NSTemporaryDirectory();

        sfilePath = [sfilePathstringByAppendingString:@"apple.html"];

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

       NSURL * filePath = [NSURLfileURLWithPath:sfilePath];

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

        [datawriteToURL:filePathatomically:YES];

        NSLog(@"Successfully saved the file to %@", filePath);

    }

   elseif ([datalength] ==0 &&

             error ==nil){

        NSLog(@"Nothing was downloaded.");

    }

   elseif (error !=nil){

        NSLog(@"Error happened = %@", error);

    }

   NSLog(@"done");

    

}


打印:

2014-06-24 16:04:19.648 cookbook7[791:a0b] will send 

2014-06-24 16:04:22.662 cookbook7[791:a0b] Error happened = Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x8c8e500 {NSErrorFailingURLStringKey=http://www.apple.com, NSErrorFailingURLKey=http://www.apple.com, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x899b800 "The request timed out."}

2014-06-24 16:04:22.664 cookbook7[791:a0b] done


如何利用GCD实现异步

-(void)AsynWithGCD

{

    NSLog(@"before gcd");

    dispatch_queue_t dispatchQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

   dispatch_async(dispatchQueue, ^(void) {

        

       NSString *urlAsString =@"http://www.apple.com";

       NSURL *url = [NSURLURLWithString:urlAsString];

        //这里初始化时设定超时

        //    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

       NSURLRequest *urlRequest = [NSURLRequestrequestWithURL:url

                                                   cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData

                                               timeoutInterval:30.0f];

       NSURLResponse *response =nil;

       NSError *error =nil;

        NSLog(@"will send ");

       NSData * data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];

        

        

       if ([datalength] >0 && error ==nil){

            /* Append the filename to the documents directory */

            //             NSURL *filePath =

            //             [[self documentsFolderUrl]

            //              URLByAppendingPathComponent:@"apple.html"];

           NSString * sfilePath =NSTemporaryDirectory();

            sfilePath = [sfilePathstringByAppendingString:@"apple.html"];

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

           NSURL * filePath = [NSURLfileURLWithPath:sfilePath];

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

            [datawriteToURL:filePathatomically:YES];

            NSLog(@"Successfully saved the file to %@", filePath);

        }

       elseif ([datalength] ==0 &&

                 error ==nil){

            NSLog(@"Nothing was downloaded.");

        }

       elseif (error !=nil){

           NSLog(@"Error happened = %@", error);

        }

       NSLog(@"done");

    });

    NSLog(@"after gcd");

}


打印:

2014-06-24 16:11:24.589 cookbook7[830:a0b] before gcd

2014-06-24 16:11:24.590 cookbook7[830:a0b] after gcd

2014-06-24 16:11:24.590 cookbook7[830:1403] will send 

2014-06-24 16:11:24.620 cookbook7[830:1403] Error happened = Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x896c130 {NSErrorFailingURLStringKey=http://www.apple.com, NSErrorFailingURLKey=http://www.apple.com, NSLocalizedDescription=The Internet connection appears to be offline., NSUnderlyingError=0xdb34e00 "The Internet connection appears to be offline."}

2014-06-24 16:11:24.620 cookbook7[830:1403] done


11.4. Modifying a URL Request with NSMutableURLRequest

修改URLRequest的属性

    NSString *urlAsString= @"http://www.apple.com";

    NSURL *url = [NSURL URLWithString:urlAsString];

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];

    [urlRequest setTimeoutInterval:30.0f];

    [urlRequest setURL:url];

0 0
原创粉丝点击