iOS 队列请求-超实用

来源:互联网 发布:unity3d宣传片 编辑:程序博客网 时间:2024/06/10 17:18

用法解析:

比如我现在要到服务端请求十几个pdf文件,下载到本地Document目录,那么用这个就非常好,

好处一:不会卡死主线程

好处二:下载完成有回调,可以在下载完成后,做一些刷新UI的操作,爽歪歪。


实例操作:

-(void)downloadPdfFileWithUrl:(NSArray *)modelList{

    if(self.config.hasUpdateData)return;

   NSMutableArray *mutableOperations = [NSMutableArrayarray];

   int countIndex = 0;

    for (MMPGetManualElementManualList *Modelin modelList)

    {

       NSString *fileName = Model.manualName;

        [[NSUserDefaultsstandardUserDefaults] setValue:fileNameforKey:[NSStringstringWithFormat:@"%@%d",fileNameKey,countIndex]];

       NSString *pdf_diret = Model.annexPath;

        

       NSString *fileContentPath = [selfgetManualPath];

       NSString *pdf_loc_path = pdf_diret.lastPathComponent;

        

       NSString *pdf_url_path = [NSStringstringWithFormat:@"%@/%@",baseURL,pdf_diret];

       NSString *abusolutePath = [fileContentPath stringByAppendingPathComponent:pdf_loc_path];

        

        [pdf_path_arrayaddObject:pdf_loc_path];

        

        countIndex++;

        

       BOOL existFile = [[NSFileManagerdefaultManager] fileExistsAtPath:abusolutePathisDirectory:NO];

       if (existFile && [selffileSizeAtPath:abusolutePath] == 0) {

            [selfremoveFileAtPath:abusolutePath];

        }elseif(existFile){

           continue;

        }

        

        NSURLRequest* request = [NSURLRequestrequestWithURL:[NSURLURLWithString:[pdf_url_path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ]cachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:60.f];

        AFHTTPRequestOperation *operation =   [[AFHTTPRequestOperationalloc] initWithRequest:request];

        [operationsetOutputStream: [NSOutputStreamoutputStreamToFileAtPath:abusolutePath append:NO]];

        [mutableOperationsaddObject:operation];

    }

    


   __block CGFloat progress =0.0f;

   NSArray *operations = [AFURLConnectionOperationbatchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations,NSUInteger totalNumberOfOperations) {

        progress = (float)numberOfFinishedOperations/totalNumberOfOperations;

      NSLog(@"%f complete", progress);

    }completionBlock:^(NSArray *operations) {

        NSLog(@"All operations in batch complete");

        MMActivityIndicator_stop();

        self.service.customLoadingHint =NO;

        self.config.hasUpdateData =YES;

    }];

    


    

    [[NSOperationQueuemainQueue] addOperations:operationswaitUntilFinished:NO];

}


0 0