#import "ViewController.h" #import "MyMD5.h" @interface ViewController () { UIImageView *imgview; UIButton *loadbtn; float loadedFileSize; float totalFileSize; } @property(nonatomic,retain)NSMutableData *mutableData; @property(nonatomic,retain)NSFileHandle *fileHandle; @property(nonatomic,retain) NSURLConnection*httpRequest; @end @implementation ViewController - (void)viewDidLoad { imgview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 40, 300, 300)]; imgview.backgroundColor=[UIColor redColor]; [self.view addSubview:imgview]; loadbtn =[[UIButton alloc]initWithFrame:CGRectMake(100, 350, 110, 110)]; [loadbtn setTitle:@"下載圖片" forState:UIControlStateNormal]; loadbtn.backgroundColor=[UIColor blueColor]; [loadbtn addTarget:self action:@selector(loadImage:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:loadbtn]; //首先判斷是否已經下載過,而後告知服務器從哪裏下載, // (1)下載前須要先肯定路徑 // 獲取文件在沙盒中Documents下的全路徑 //咱們把url做爲文件名字-》可是url 中可能存在一些非法字符不能做爲文件名,這時咱們能夠用md5 對文件名進行加密 產生一個惟一的字符串 (十六進制的數字+A-F表示),這樣就能夠保證文件名不出現非法字符 NSString *url = [NSString stringWithFormat:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"]; NSString *fileName = [MyMD5 md5:url];//MD5 NSLog(@"------------%@",fileName); //獲取Documents NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; //拼接路徑 NSString *filePath = [docPath stringByAppendingPathComponent:fileName]; NSLog(@"-------------path:%@",filePath); // ***這裏須要用到OC文件管理的知識! //建立文件(首先檢測有沒有存在,若是沒有在建立) if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { //檢測文件是否存在 //不存在那麼要建立 //NSFileManager 文件管理句柄 [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; } //若是已存在獲取已近下載的大小,若是不存在那麼大小爲0; NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; //保存已經下載文件的大小 //loadedFileSize = fileSize; //下載前須要打開文件 self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; //*****(若是服務器支持可變斷點續傳能夠照用,若是不支持請忽略 頭域) //把文件大小告知服務器 //建立可變請求 增長請求頭 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; //增長頭域 告知服務器 從 哪一個字節以後開始下載(不瞭解頭域的仍是那句話百度),不支持頭域的能夠直接跳過 // [request addValue:[NSString stringWithFormat:@"bytes=%llu-",fileSize] forHTTPHeaderField:@"Range"]; //建立請求鏈接 開始異步下載 _httpRequest = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } // NSURLConnectionDataDelegate //接收服務器響應 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 在這裏咱們能夠計算文件的總大小,獲取數據的類型 : httpResponse.MIMEType ,數據的大小: NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; // NSLog(@"url:%@",httpResponse.URL.absoluteString); //計算文件總大小 = 已經下載的+服務器將要發的 //( self.loadedFileSize和上面關聯着 數據是一段一段下載的) totalFileSize = loadedFileSize+httpResponse.expectedContentLength; } //接收數據過程 一段一段接收 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //都是OC文件管理的知識,我就不細說了吧 //下載一段 寫一段數據 //先把文件偏移量定位到文件尾 [_fileHandle seekToEndOfFile]; //寫文件 [_fileHandle writeData:data]; //當即同步到磁盤 [_fileHandle synchronizeFile]; //記錄已經下載數據大小 loadedFileSize += data.length; imgview.image =[UIImage imageWithData:data]; } //下載完成必定要關閉呀 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self stopDownload];//中止下載 } //下載失敗也要關閉呀 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self stopDownload]; } - (void)stopDownload { if (_httpRequest) { [_httpRequest cancel]; _httpRequest = nil; } [_fileHandle closeFile];//關閉文件 } - (void)loadImage:(id)sender { /** * @author aiqing, 17-11-19 16:11:24 *第一種方法: * NSURL *url = [NSURL URLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"]; dispatch_queue_t queue =dispatch_queue_create("loadImage",NULL); dispatch_async(queue, ^{ NSData *resultData = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:resultData]; dispatch_sync(dispatch_get_main_queue(), ^{ imgview.image = img; }); }); */ /** * @author aiqing, 17-11-19 16:11:58 * *第二種方法: NSURL *url = [NSURL URLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"]; NSData *resultData = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:resultData]; imgview.image = img; */ /** * @author aiqing, 17-11-19 17:11:01 * *第三種方法(異步下載:)要走下面的代理方法 NSURL *url = [NSURL URLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"GET"]; //設置請求方式 [request setTimeoutInterval:60];//設置超時時間 self.mutableData = [[NSMutableData alloc] init]; [NSURLConnection connectionWithRequest:request delegate:self];//發送一個異步請求 */ } #pragma mark - NSURLConnection delegate //數據加載過程當中調用,獲取數據 //- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // [self.mutableData appendData:data]; //} // ////數據加載完成後調用 //- (void)connectionDidFinishLoading:(NSURLConnection *)connection { // UIImage *image = [UIImage imageWithData:self.mutableData]; // imgview.image = image; //} // //- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // NSLog(@"請求網絡失敗:%@",error); //}