11.0. Introduction(Networking, JSON, XML, and Sharing)
NSURLConnection 因特网连接和收发数据
NSJSONSerialization JSON 数据的系列化和反系列化
NSXMLParser XML数据的解析
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:&response error:&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:&response error:&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:&response error:&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];