同步与异步调用http请求 iphone开发
2012-07-12 10:46
225 查看
[align=left]异步: [/align] NSMutableData* buf = [[NSMutableData alloc] initWithLength:0]; [align=left]NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self]; [/align] [align=left] [/align] [align=left]// 收到响应时, 会触发 [/align] [align=left]- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse; [/align] [align=left]// 你可以在里面判断返回结果, 或者处理返回的http头中的信息 [/align] [align=left] [/align] [align=left]// 每收到一次数据, 会调用一次 [/align] [align=left]- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data; [/align] [align=left]// 因此一般来说,是 [/align] [align=left]- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data [/align] [align=left]{ [/align] [align=left][buf appendData:data]; [/align] [align=left]} [/align] [align=left]// 当然buffer就是前面initWithRequest时同时声明的. [/align] [align=left] [/align] [align=left]// 网络错误时触发 [/align] [align=left]- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error; [/align] [align=left] [/align] [align=left]// 全部数据接收完毕时触发 [/align] [align=left]- (void)connectionDidFinishLoading:(NSURLConnection *)aConn; [/align] [align=left] [/align] |
//.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");
}
[align=left]第二段是同步请求[/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
[align=left] [/align]
,~ // 初始化请求 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];
相关文章推荐
- [转]同步与异步调用http请求 iphone开发
- 同步与异步调用http请求 iphone开发
- iPhone开发中如何异步调用web service
- 同步与异步调用http请求&nbsp;iphone开…
- iPhone开发中如何异步调用web service
- iphone 开发第七天 - IOS之同步请求、异步请求、GET请求、POST请求
- iOS开发-如何用GCD同步若干个异步调用?
- 软件中的1、同步调用;2、回调;3、异步调用
- AJAX 同步调用与异步调用的问题
- 同步调用、回调和异步调用区别
- 【iOS开发-91】GCD的同步异步串行并行、NSOperation和NSOperationQueue一级用dispatch_once实现单例
- [IPhone开发]发送Http请求(POST GET)的方法
- 同步调用与异步调用
- AJAXPro用法,关于JS同步和异步调用后台代码的学习
- AngularJS中的http请求默认为异步的,请问如何设置为同步请求呢?--使用$q
- 回调函数,同步调用,异步调用,事件,消息循环
- iPhone开发 构建View 时用到代理函数调用顺序 图解
- MacOS和iOS开发中异步调用与多线程的区别
- IO中同步、异步与阻塞、非阻塞的区别 分类: 嵌入式开发学习 2014-04-11 13:47 193人阅读 评论(0) 收藏