iOS異步請求下載圖片

ccwv 10年前發布 | 7K 次閱讀 Objective-C IOS

在iOS中可以這樣獲取一張網絡圖片

    NSURL *url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D2048/sign=91c1063e1f950a7b753549c43ee963d9/f31fbe096b63f624b6a9640b8544ebf81b4ca3c6.jpg"];  
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];  
    UIImage *img = [UIImage imageWithData:data];  

但是圖片比較大的時候程序會卡在這里,所以我們要用異步請求來下載圖片

1.新建一個single view工程

2.ViewController.h文件:

    @interface ViewController : UIViewController <NSURLConnectionDataDelegate> {  
        NSMutableData* _imageData;//如果圖片比較大的話,response會分幾次返回相應數據,所以需要用NSMutableData來接受數據  
        float _length;  
    }  
    @end  

3.ViewController.m文件:

    - (void)viewDidLoad
{
[super viewDidLoad];

    //初始化圖片數據  
    _imageData = [[NSMutableData alloc] init];  

    //請求  
    NSURL *url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D2048/sign=91c1063e1f950a7b753549c43ee963d9/f31fbe096b63f624b6a9640b8544ebf81b4ca3c6.jpg"];  
    NSURLRequest *request = [NSURLRequest requestWithURL:url];  
    //連接  
    [NSURLConnection connectionWithRequest:request delegate:self];  
}  </pre> 


4.接受響應頭和響應體

    //響應頭

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
{  
    //清空圖片數據  
    [_imageData setLength:0];  
    //強制轉換  
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;  
    _length = [[resp.allHeaderFields objectForKey:@"Content-Length"] floatValue];  
    //設置狀態欄接收數據狀態  
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
}  

//響應體  
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
{  
    [_imageData appendData:data];//拼接響應數據  
}  </pre> 


5.請求完成之后將圖片顯示出來,并且設置狀態欄

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
    {  
        UIImage* image = [UIImage imageWithData:_imageData];  
        self.view.backgroundColor = [UIColor colorWithPatternImage:image];  
        //設置狀態欄  
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
    }  

 本文由用戶 ccwv 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!