iphone http下载文件

长平狐 发布于 2013/12/25 17:17
阅读 78
收藏 0

头文件noteHttp.h

#import <Foundation/Foundation.h>
@interface NoteHttp : NSObject{
    //urlfbfh
    NSString *urlString;
    //下载的数据
    NSMutableData *dataNote;
}
@property(nonatomic,retain) NSString *urlString;
@property(nonatomic,retain)NSMutableData *dataNote;
-(void)down;
@end

实现文件 noteHttp.m

#import "NoteHttp.h"
@implementation NoteHttp
@synthesize urlString,dataNote,noteXml;
- (id)init {
    self = [super init];
    if (!self) {
        [self release];
        return nil;
    }
    urlString=[[NSString alloc]init];
    dataNote=[[NSMutableData alloc]init];
    return self;
}
-(void)down{
    //http地址
    urlString=@"http://192.168.67.3:8080/Todo/note.xml";
    //转成NSURL,
    NSURL *url=[NSURL URLWithString:urlString];
    //负载请求
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
    //异步请求,通过一个delegate来做数据的下载以及Request的接受等等消息,此处delegate:self,所以需要本类实现一些方法,并且定义receivedData做数据的接受
    NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection release];
    [request release];
    /*
     但是异步模式下带来了一个新的问题,很多情况下,网络请求不在主线程,或者界面等待网络结果,不在主线程的时候,调用线程如果生命周期over,下面这些可能都没有调用到,导致得不到想要得效果,所以需要在NSURLConnection请求后面加点东西来阻塞
     while(!finished) {
     
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]];
     
     }
     */
}
//从网络上下载的数据,直到数据全部下载完成
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data{
    [self.dataNote appendData:data];
}
//http交互正常,完成。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //沙盒路径
    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"note.xml"];

    //当完成交互,也就是说数据下载完成时,就创建该文件
    [[NSFileManager defaultManager]createFileAtPath:path contents:dataNote attributes:nil];
}

//网络连接不成功,出现异常。
- (void)connection:(NSURLConnection *)connection 
  didFailWithError:(NSError *)error
{
    //如果出现异常,弹出对话框给出原因
    UIAlertView *errorAlert = [[UIAlertView alloc]
							   initWithTitle: [error localizedDescription]
							   message: [error localizedFailureReason]
							   delegate:nil
							   cancelButtonTitle:@"OK"
							   otherButtonTitles:nil];
	[errorAlert show];
	[errorAlert release];

}
-(void)dealloc{
    [urlString release];
    [dataNote release];
    [super dealloc];
}
@end


ok!实现!本博客是我自己的练习,有好多地方没有讲太清楚,还请谅解!


原文链接:http://blog.csdn.net/rhljiayou/article/details/7616365
加载中
返回顶部
顶部