异步: NSMutableData* buf = [[NSMutableData alloc] initWithLength:0]; NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self]; // 收到响应时, 会触发 - (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse; // 你可以在里面判断返回结果, 或者处理返回的http头中的信息 // 每收到一次数据, 会调用一次 - (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data; // 因此一般来说,是 - (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data { [buf appendData:data]; } // 当然buffer就是前面initWithRequest时同时声明的. // 网络错误时触发 - (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error; // 全部数据接收完毕时触发 - (void)connectionDidFinishLoading:(NSURLConnection *)aConn; |
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//.h file:
//
// DownloadHelper.h
// BigViewApp
//
// Created by lu Yinghuai on 11-2-14.
// Copyright 2011 minesage. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol DownloadHelperDelegate;
@interface DownloadHelper : NSObject {
@private
NSURLConnection *appListFeedConnection;
NSMutableData *appListData;
NSString *strResultData;
id <DownloadHelperDelegate> delegate;
}
-(id)initWithDelegate: (id <DownloadHelperDelegate>)theDelegate;
-(void) startDownload: (NSString *) targetUrl;
@property (nonatomic, assign) id <DownloadHelperDelegate> delegate;
@property (nonatomic, retain) NSURLConnection *appListFeedConnection;
@property (nonatomic, retain) NSMutableData *appListData;
@property (nonatomic, retain) NSString *strResultData;
@end
@protocol DownloadHelperDelegate
- (void)didFinishDownload:(NSString *) strResult;
- (void)downloadErrorOccurred:(NSError *) error;
@end
//.m file
//
// DownloadHelper.m
// BigViewApp
//
// Created by lu Yinghuai on 11-2-14.
// Copyright 2011 minesage. All rights reserved.
//
#import "DownloadHelper.h"
@implementation DownloadHelper
@synthesize appListFeedConnection, appListData,delegate,strResultData;
- (id)initWithDelegate:(id <DownloadHelperDelegate>)theDelegate
{
self = [super init];
if (self != nil)
{
self.delegate = theDelegate;
//strResultData = [[NSString alloc] init];
}
return self;
}
-(void) startDownload: (NSString *) targetUrl {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:targetUrl]];
self.appListFeedConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
// Test the validity of the connection object. The most likely reason for the connection object
// to be nil is a malformed URL, which is a programmatic error easily detected during development
// If the URL is more dynamic, then you should implement a more flexible validation technique, and
// be able to both recover from errors and communicate problems to the user in an unobtrusive manner.
//
NSAssert(self.appListFeedConnection != nil, @"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
#pragma mark -
#pragma mark NSURLConnection delegate methods
// -------------------------------------------------------------------------------
// handleError:error
// -------------------------------------------------------------------------------
- (void)handleError:(NSError *)error
{
/*NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot Show Top Paid Apps"
message:errorMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];*/
[delegate downloadErrorOccurred:error];
}
// The following are delegate methods for NSURLConnection. Similar to callback functions, this is how
// the connection object, which is working in the background, can asynchronously communicate back to
// its delegate on the thread from which it was started - in this case, the main thread.
//
// -------------------------------------------------------------------------------
// connection:didReceiveResponse:response
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.appListData = [NSMutableData data]; // start off with new data
}
// -------------------------------------------------------------------------------
// connection:didReceiveData:data
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[appListData appendData:data]; // append incoming data
}
// -------------------------------------------------------------------------------
// connection:didFailWithError:error
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfo];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
self.appListFeedConnection = nil; // release our connection
}
// -------------------------------------------------------------------------------
// connectionDidFinishLoading:connection
// -------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.appListFeedConnection = nil; // release our connection
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
strResultData = [[NSString alloc] initWithData:appListData encoding:NSASCIIStringEncoding];
NSLog(@"%@",strResultData);
[delegate didFinishDownload:strResultData];
self.appListData = nil;
}
// -------------------------------------------------------------------------------
// dealloc
// -------------------------------------------------------------------------------
- (void)dealloc
{
[appListFeedConnection release];
[appListData release];
[strResultData release];
[super dealloc];
}
@end
//.m 调用代码
1.实例化:
//download 排行榜
downLoadHelper = [[DownloadHelper alloc] initWithDelegate:self];
2.//下载排行榜数据
[downLoadHelper startDownload: @"http://www.google.com/trends/hottrends/atom/hourly"];
3.委托对象回调方法
#pragma mark ------ DownloadHelper Delegate Method ------
- (void) didFinishDownload:(NSString *) strResult{
NSLog(@"didFinishDownload");
[hotTrend.keyWordRecordList removeAllObjects];
NSLog(@"%@",strResult);
}
-(void) downloadErrorOccurred:(NSError *) error{
NSLog(@"downloadErrorOccurred");
}
//
// DownloadHelper.h
// BigViewApp
//
// Created by lu Yinghuai on 11-2-14.
// Copyright 2011 minesage. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol DownloadHelperDelegate;
@interface DownloadHelper : NSObject {
@private
NSURLConnection *appListFeedConnection;
NSMutableData *appListData;
NSString *strResultData;
id <DownloadHelperDelegate> delegate;
}
-(id)initWithDelegate: (id <DownloadHelperDelegate>)theDelegate;
-(void) startDownload: (NSString *) targetUrl;
@property (nonatomic, assign) id <DownloadHelperDelegate> delegate;
@property (nonatomic, retain) NSURLConnection *appListFeedConnection;
@property (nonatomic, retain) NSMutableData *appListData;
@property (nonatomic, retain) NSString *strResultData;
@end
@protocol DownloadHelperDelegate
- (void)didFinishDownload:(NSString *) strResult;
- (void)downloadErrorOccurred:(NSError *) error;
@end
//.m file
//
// DownloadHelper.m
// BigViewApp
//
// Created by lu Yinghuai on 11-2-14.
// Copyright 2011 minesage. All rights reserved.
//
#import "DownloadHelper.h"
@implementation DownloadHelper
@synthesize appListFeedConnection, appListData,delegate,strResultData;
- (id)initWithDelegate:(id <DownloadHelperDelegate>)theDelegate
{
self = [super init];
if (self != nil)
{
self.delegate = theDelegate;
//strResultData = [[NSString alloc] init];
}
return self;
}
-(void) startDownload: (NSString *) targetUrl {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:targetUrl]];
self.appListFeedConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
// Test the validity of the connection object. The most likely reason for the connection object
// to be nil is a malformed URL, which is a programmatic error easily detected during development
// If the URL is more dynamic, then you should implement a more flexible validation technique, and
// be able to both recover from errors and communicate problems to the user in an unobtrusive manner.
//
NSAssert(self.appListFeedConnection != nil, @"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
#pragma mark -
#pragma mark NSURLConnection delegate methods
// -------------------------------------------------------------------------------
// handleError:error
// -------------------------------------------------------------------------------
- (void)handleError:(NSError *)error
{
/*NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot Show Top Paid Apps"
message:errorMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];*/
[delegate downloadErrorOccurred:error];
}
// The following are delegate methods for NSURLConnection. Similar to callback functions, this is how
// the connection object, which is working in the background, can asynchronously communicate back to
// its delegate on the thread from which it was started - in this case, the main thread.
//
// -------------------------------------------------------------------------------
// connection:didReceiveResponse:response
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.appListData = [NSMutableData data]; // start off with new data
}
// -------------------------------------------------------------------------------
// connection:didReceiveData:data
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[appListData appendData:data]; // append incoming data
}
// -------------------------------------------------------------------------------
// connection:didFailWithError:error
// -------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfo];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
self.appListFeedConnection = nil; // release our connection
}
// -------------------------------------------------------------------------------
// connectionDidFinishLoading:connection
// -------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.appListFeedConnection = nil; // release our connection
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
strResultData = [[NSString alloc] initWithData:appListData encoding:NSASCIIStringEncoding];
NSLog(@"%@",strResultData);
[delegate didFinishDownload:strResultData];
self.appListData = nil;
}
// -------------------------------------------------------------------------------
// dealloc
// -------------------------------------------------------------------------------
- (void)dealloc
{
[appListFeedConnection release];
[appListData release];
[strResultData release];
[super dealloc];
}
@end
//.m 调用代码
1.实例化:
//download 排行榜
downLoadHelper = [[DownloadHelper alloc] initWithDelegate:self];
2.//下载排行榜数据
[downLoadHelper startDownload: @"http://www.google.com/trends/hottrends/atom/hourly"];
3.委托对象回调方法
#pragma mark ------ DownloadHelper Delegate Method ------
- (void) didFinishDownload:(NSString *) strResult{
NSLog(@"didFinishDownload");
[hotTrend.keyWordRecordList removeAllObjects];
NSLog(@"%@",strResult);
}
-(void) downloadErrorOccurred:(NSError *) error{
NSLog(@"downloadErrorOccurred");
}
第二段是同步请求
,~// 初始化请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// 设置URL
[request setURL:[NSURL URLWithString:urlStr]];
// 设置HTTP方法
[request setHTTPMethod:@"GET"];
// 发 送同步请求, 这里得returnData就是返回得数据了
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
// 释放对象
[request release];