iOS图片加载

#import “ViewController.h”

@interface ViewController () <NSURLConnectionDataDelegate> {

    NSURLRequest    *_request;

    NSURLConnection *_conn;

    NSMutableData   *_recieveData;

    long long       _expectedLeght;

}

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

@property (assign, nonatomic) BOOL isLoadFinish;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    self.imageView.userInteractionEnabled = YES;

    [self updateImage];

}

– (void)updateImage{

    NSString *url = @”http://images.ali213.net/picfile/pic/2013/03/01/82.jpg”;

    //开始写代码,初始化NSURLRequestNSURLConnection

    _request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:url]];

    _conn = [[NSURLConnection alloc]initWithRequest:_request delegate:self];

    _recieveData = [[NSMutableData alloc] init];

    self.isLoadFinish = false;

}

#pragma mark –

#pragma mark NSURLConnectionDataDelegate

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    _expectedLeght = response.expectedContentLength;

    NSLog(@”expected Length: %lld”, _expectedLeght);

}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@”Connection %@ error, error info: %@”, connection, error);

}

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

{

        [_recieveData appendData:data];

        self.isLoadFinish = false;

    if (_expectedLeght == _recieveData.length) {

        self.isLoadFinish = true;

        self.imageView.image = [UIImage imageWithData:_recieveData];

    }

}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSLog(@”Connection Loading Finished!!!”);

}

@end

分享到: 更多
Separator image Posted in IOS.