iOS NSURLConnection同步 异步请求 代理

注意:

self.allData 跟  _allData 在这个里面是一样的  但是涉及到内存管理  self.allData 会占用一次 retain  retainCount会+1  而 _allData 不会  


//.h


@interface ViewController :UIViewController<NSURLConnectionDataDelegate>

{

    

}

@property (retain,nonatomic) IBOutletUIImageView *viewImage;

@property(nonatomic,retain)NSMutableData *allData;


//      .m

@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

//http://z.abang.com/f/dslr/1/3/M/3/-/-/001.jpg

    NSString *imageFile =@"http://sjrjy.apkzz.net/201009/17115639e6c12f45db3765.jpg";

    

   NSURL *imageUrl = [NSURLURLWithString:imageFile];

   NSURLRequest *requst = [NSURLRequestrequestWithURL:imageUrl];

    //同步请求小数据量时候适合(只有这里执行且成功的收到数据才继续执行)

//    NSData *data = [NSURLConnection sendSynchronousRequest:requst returningResponse:nil error:nil];

//    if(data)

//    {

//        _viewImage.image = [UIImage imageWithData:data];

//        //获取到xx.app 这个包

//        NSBundle *bundle = [NSBundle mainBundle].bundlePath;

//        NSString *filePath = [NSString stringWithFormat:@"%@/bundle.jpg",bundle];

//        //存数据

//        [data writeToFile:filePath atomically:YES];

//        

//    }

    

    

    //异步请求 大数据量的情况

    [NSURLConnectionconnectionWithRequest:requstdelegate:self];

    

}

#pragma mark -

//连接服务器得到响应时候回调该方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"didReceiveResponse");

    self.allData = [[[NSMutableDataalloc]init]autorelease];

    //获取数据总长度 进度条

   // response.expectedContentLength

}

//收到数据时候回调该方法(一点一点的收到数据--》会被调用多次)

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    //慢慢的收到数据 收集起来

    [self.allDataappendData:data];

    //当前数据长度

    //self.allData.length

    NSLog(@"didReceiveData");

}

//数据全部收到后回调

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    _viewImage.image = [UIImageimageWithData:self.allData];

    NSLog(@"connectionDidFinishLoading");


}

//连接错误时候回调

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"connect fail ! error:%@",error);

}





- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)dealloc {

    [_viewImage release];

    [_allDatarelease];

    [superdealloc];

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值