One: Direct download using NSData:
//This method cannot be paused, only suitable for downloading small filesNsurl*url = [[Nsurl alloc] initwithstring:@"Http://120.25.226.186:32812/resources/images/minion_15.png" ]; NSData*data =[NSData datawithcontentsofurl:url options:kniloptions Error:nil]; UIImage*image =[UIImage Imagewithdata:data]; Uiimageview*imageview =[[Uiimageview alloc] initwithimage:image]; Imageview.frame= CGRectMake (0,0, $, $); [Self.view Addsubview:imageview];
Two: Using Nsurlconnect
Nsurl *url = [[Nsurl alloc] initwithstring:@"Http://120.25.226.186:32812/resources/images/minion_15.png" ]; Nsurlrequest*request =[[Nsurlrequest alloc] initwithurl:url]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler:^ (Nsurlresponse * _nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) {UIImage*image =[UIImage Imagewithdata:data]; Uiimageview*imageview =[[Uiimageview alloc] initwithimage:image]; Imageview.frame= CGRectMake (0,0, $, $); [Self.view Addsubview:imageview]; }];}
Three: The use of splicing agent method to download
This method can only be used to download small files as well as above.
#import "ViewController.h"@interfaceViewcontroller () <NSURLConnectionDataDelegate>@property (nonatomic, strong) Nsmutabledata*fileData; @property (nonatomic, assign) Nsinteger contentlength;//@property (nonatomic, strong) UIImage *image;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //This method cannot be paused, only suitable for downloading small filesNsurl*url = [[Nsurl alloc] initwithstring:@"Http://120.25.226.186:32812/resources/videos/minion_15.mp4" ]; Nsurlrequest*request =[[Nsurlrequest alloc] initwithurl:url]; //to set up a proxy for connect[Nsurlconnection Connectionwithrequest:requestDelegate: self];}#pragmaMark-nsurlconnect's agent//connection receive a response, you should create a data-ready mosaic- (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nshttpurlresponse *) response{Nshttpurlresponse*newresponse =response; //get the total length of the fileSelf.contentlength = [newresponse.allheaderfields[@"Content-length"] IntegerValue]; Self.filedata=[Nsmutabledata data];}//after receiving the data, this method will be called multiple times, you need to splice the data here- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[Self.filedata Appenddata:data]; CGFloat per= (1.0* Self.fileData.length/self.contentlength); NSLog (@"%f", per);}//Download Complete- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSLog (@"%zd", self.fileData.length);}
2016-1-23 Small file download