(转 http://blog.csdn.net/rhljiayou/article/details/7616365)
头文件noteHttp.h
1 #import <Foundation/Foundation.h> 2 @interface NoteHttp : NSObject{ 3 //urlfbfh 4 NSString *urlString; 5 //下载的数据 6 NSMutableData *dataNote; 7 } 8 @property(nonatomic,retain) NSString *urlString; 9 @property(nonatomic,retain)NSMutableData *dataNote; 10 -(void)down; 11 @end
实现文件 noteHttp.m
1 #import "NoteHttp.h" 2 @implementation NoteHttp 3 @synthesize urlString,dataNote,noteXml; 4 - (id)init { 5 self = [super init]; 6 if (!self) { 7 [self release]; 8 return nil; 9 } 10 urlString=[[NSString alloc]init]; 11 dataNote=[[NSMutableData alloc]init]; 12 return self; 13 } 14 -(void)down{ 15 //http地址 16 urlString=@"http://192.168.67.3:8080/Todo/note.xml"; 17 //转成NSURL, 18 NSURL *url=[NSURL URLWithString:urlString]; 19 //负载请求 20 NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url]; 21 //异步请求,通过一个delegate来做数据的下载以及Request的接受等等消息,此处delegate:self,所以需要本类实现一些方法,并且定义receivedData做数据的接受 22 NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self]; 23 [connection release]; 24 [request release]; 25 /* 26 但是异步模式下带来了一个新的问题,很多情况下,网络请求不在主线程,或者界面等待网络结果,不在主线程的时候,调用线程如果生命周期over,下面这些可能都没有调用到,导致得不到想要得效果,所以需要在NSURLConnection请求后面加点东西来阻塞 27 while(!finished) { 28 29 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]]; 30 31 } 32 */ 33 } 34 //从网络上下载的数据,直到数据全部下载完成 35 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data{ 36 [self.dataNote appendData:data]; 37 } 38 //http交互正常,完成。 39 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 40 { 41 //沙盒路径 42 NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 43 NSString *documentsDirectory = [paths objectAtIndex:0]; 44 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"note.xml"]; 45 46 //当完成交互,也就是说数据下载完成时,就创建该文件 47 [[NSFileManager defaultManager]createFileAtPath:path contents:dataNote attributes:nil]; 48 } 49 50 //网络连接不成功,出现异常。 51 - (void)connection:(NSURLConnection *)connection 52 didFailWithError:(NSError *)error 53 { 54 //如果出现异常,弹出对话框给出原因 55 UIAlertView *errorAlert = [[UIAlertView alloc] 56 initWithTitle: [error localizedDescription] 57 message: [error localizedFailureReason] 58 delegate:nil 59 cancelButtonTitle:@"OK" 60 otherButtonTitles:nil]; 61 [errorAlert show]; 62 [errorAlert release]; 63 64 } 65 -(void)dealloc{ 66 [urlString release]; 67 [dataNote release]; 68 [super dealloc]; 69 } 70 @end