IOS development-How files are downloaded

Source: Internet
Author: User

    • File Upload
  1. Create File Upload class FileDownload.h
    // //   FileDownload.h//  01. File Download ////  Created by Wyh on 15-1-29.//  Copyright (c) 2015 Itcast. All rights reserved. // #import <Foundation/Foundation.h>@interface  filedownload:nsobject-(  void) Downloadfilewithurl: (nsurl *) URL completion: (void (^) (UIImage *image)) completion; @end

  2. Create File Upload class FILEDOWNLOAD.M
    ////FILEDOWNLOAD.M//01. File Download////Created by Wyh on 15-1-29.//Copyright (c) 2015 Itcast. All rights reserved.//#import "FileDownload.h"#import "nsstring+password.h"#defineKtimeout 2.0f//number of bytes downloaded per download#defineKbytespertimes 20250@interfacefiledownload () @property (nonatomic, strong) NSString*Cachefile, @property (nonatomic, strong) UIImage*Cacheimage;@end@implementationFileDownload/** In order to ensure that the development of the simple, all methods do not use multi-threading, all the attention is maintained in the file download in the development if you encounter a comparison of computational problems, it is recommended that: 1> test data is not too large 2> test data changes, you can use written calculation to calculate the accurate value 3> Writing code-controlled tests*///-(NSString *) Cachefile//{//if (!_cachefile) {//nsstring *cachedir = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) [0];//_cachefile = [Cachedir stringbyappendingpathcomponent:@ "123.png"];//    }//return _cachefile;//}-(UIImage *) cacheimage{if(!_cacheimage) {_cacheimage=[UIImage ImageWithContentsOfFile:self.cacheFile]; }    return_cacheimage;}- (void) Setcachefile: (NSString *) urlstr{NSString*cachedir = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) [0]; Urlstr=[Urlstr MD5]; _cachefile=[Cachedir stringbyappendingpathcomponent:urlstr];}- (void) Downloadfilewithurl: (nsurl *) URL completion: (void(^) (UIImage *image)) completion{//a serial queue asynchronous method in GCDdispatch_queue_t q = dispatch_queue_create ("Cn.itcast.download", dispatch_queue_serial); Dispatch_async (q,^{NSLog (@"%@", [Nsthread CurrentThread]); //The result of MD5 encryption of the URL is treated as a file nameSelf.cachefile =[url absolutestring]; //1. Download files from the network, you need to know the size of this file        Long LongFileSize =[self filesizewithurl:url]; //calculate local cache file size        Long LongCachefilesize =[self localfilesize]; if(Cachefilesize = =fileSize) {Dispatch_async (Dispatch_get_main_queue (),^{completion (self.cacheimage);            }); NSLog (@"file already exists"); return; }                //2. Determine the size of each packet        Long LongFromb =0; Long LongToB =0; //computes the number of bytes starting and ending         while(FileSize >kbytespertimes) {            //20480 + 20480//ToB = Fromb + Kbytespertimes-1; //3. Segment Download File[self Downloaddatawithurl:url fromb:fromb Tob:tob]; FileSize-=Kbytespertimes; Fromb+=Kbytespertimes; } [self Downloaddatawithurl:url fromb:fromb tob:fromb+ FileSize-1]; Dispatch_async (Dispatch_get_main_queue (),^{completion (self.cacheimage);            }); });}#pragmaMark downloads packets with a specified byte range/** nsurlrequestuseprotocolcachepolicy = 0,//default cache policy, memory cache Nsurlrequestreloadignoringlocalcachedata = 1,//Ignore Local Memory Cache Nsurlrequestreloadignoringcachedata*/- (void) Downloaddatawithurl: (nsurl *) URL Fromb: (Long Long) Fromb ToB: (Long Long) tob{NSLog (@"data packet:%@", [Nsthread CurrentThread]); Nsmutableurlrequest*request =[nsmutableurlrequest requestwithurl:url cachepolicy:nsurlrequestreloadignoringcachedata TimeoutInterval:        Ktimeout]; //Specify the range of bytes to get in the requestNSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld", Fromb, ToB]; [Request Setvalue:range Forhttpheaderfield:@"Range"]; NSLog (@"%@", Range); Nsurlresponse*response =Nil; NSData*data = [Nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:null]; //write file, overwrite file does not append//[Data writetofile:@ "/users/aplle/desktop/1.png" atomically:yes];[self appenddata:data]; NSLog (@"%@", response);}#pragmaMark-Reads the local cache file size-(Long Long) localfilesize{//read local file informationNsdictionary *dict =[[Nsfilemanager Defaultmanager] AttributesOfItemAtPath:self.cacheFile error:null]; NSLog (@"%lld", [dict[nsfilesize] longlongvalue]); return[dict[nsfilesize] longlongvalue];}#pragmaMark-Append data to File-(void) AppendData: (NSData *) data{//determine if a file existsNsfilehandle *FP =[Nsfilehandle FileHandleForWritingAtPath:self.cacheFile]; //Create file If file does not exist    if(!FP)    {[Data writeToFile:self.cacheFile atomically:yes]; } Else {        //If an append file already exists for the file//1> move to end of file[FP seektoendoffile]; //2> Append Data[FP Writedata:data]; //3> Writing Files[FP CloseFile]; }}#pragmaMark-Get Network File Size-(Long Long) Filesizewithurl: (Nsurl *) url{//The default is getNsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachepolicy:0Timeoutinterval:ktimeout]; //head Header, just returns information about the file resource and does not return specific data//If you want to get the mimetype of a resource, you must also use head, otherwise the data will be downloaded two times repeatedlyRequest. HttpMethod =@"HEAD"; //To get the file size using the synchronous methodNsurlresponse *response =Nil; [Nsurlconnection sendsynchronousrequest:request Returningresponse:&response Error:null]; //size of the Expectedcontentlength file on the networkNSLog (@"%lld", response.expectedcontentlength); returnresponse.expectedcontentlength;}@end

  3. Called in the Controller
    ////VIEWCONTROLLER.M//01. File Download////Created by Wyh on 15-1-29.//Copyright (c) 2015 Itcast. All rights reserved.//#import "ViewController.h"#warningInclude FileDownload.h file#import "FileDownload.h"@interfaceViewcontroller () @property (nonatomic, strong) FileDownload*Download, @property (weak, nonatomic) Iboutlet Uiimageview*ImageView;@end@implementationViewcontroller- (void) viewdidload{[Super Viewdidload];#warningCreate the FileDownload object and call method Downloadfilewithurl:Self.download=[[FileDownload alloc] init]; [Self.download downloadfilewithurl:[nsurl urlwithstring:@"Http://localhost/itcast/images/head4.png"] completion:^ (UIImage *image) {Self.imageView.image=image; }];}@end

IOS development-How files are downloaded

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.