- Get the downloaded file size
- -(unsigned long long) Filesizeforpath: (NSString *) path {
- signed long long fileSize = 0;
- Nsfilemanager *filemanager = [Nsfilemanager new]; //default is not thread safe
- if ([FileManager Fileexistsatpath:path]) {
- nserror *error = nil;
- nsdictionary *filedict = [FileManager attributesofitematpath:path error:&error];
- if (!error && filedict) {
- FileSize = [filedict fileSize];
- }
- }
- return fileSize;
- }
- Start download
- -(void) Startdownload {
- nsstring *downloadurl = @ "Http://www.xxx.com/xxx.zip";
- nsstring *cachedirectory = [Nssearchpathfordirectoriesindomains (nscachesdirectory, NSUserDomainMask, YES) Objectatindex:0];
- nsstring *downloadpath = [cachedirectory stringbyappendingpathcomponent:@ "Xxx.zip"];
- nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl Urlwithstring:downloadurl];
- //Check whether the file has been downloaded partially
- Unsigned long long downloadedbytes = 0;
- if ([[[Nsfilemanager Defaultmanager] Fileexistsatpath:downloadpath]) {
- //Get the downloaded file length
- Downloadedbytes = [self filesizeforpath:downloadpath];
- if (Downloadedbytes > 0) {
- nsmutableurlrequest *mutableurlrequest = [request mutablecopy];
- nsstring *requestrange = [NSString stringwithformat:@ "bytes=%llu-", downloadedbytes];
- [Mutableurlrequest setvalue:requestrange Forhttpheaderfield:@ "Range"];
- request = Mutableurlrequest;
- }
- }
- //Do not use the cache, avoid the problem of the breakpoint continued to pass
- [[Nsurlcache Sharedurlcache] removecachedresponseforrequest:request];
- //Download Request
- afhttprequestoperation *operation = [[afhttprequestoperation alloc] initwithrequest:request];
- //download Path
- Operation. outputstream = [Nsoutputstream outputstreamtofileatpath:downloadpath append:YES];
- //Download Progress callback
- [Operation setdownloadprogressblock:^ (Nsuinteger bytesread, long Long totalbytesread, long long Totalbytesexpectedtoread) {
- //Download Progress
- Float progress = ((float) Totalbytesread + downloadedbytes)/(Totalbytesexpectedtoread + downloadedbytes);
- }];
- //Success and failure callbacks
- [Operation setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, ID responseobject) {
- } failure:^ (afhttprequestoperation *operation, nserror *error) {
- }];
- [Operation start];
- }
It is important to note that this is only useful for downloading zip packages, because there may be too many data to download files in other formats. When the file has been downloaded, call the function again, unable to determine whether the file has been downloaded completely, so it will be downloaded again, the server will report 416 error, the return will also output to the file, so that the file size is abnormal. However, the ZIP format is not affected.
Afnetworking to implement a breakpoint when the program restarts