分享

AFNetworking Block下载文件保存到沙盒

 没原创_去搜索 2015-07-29
+ (void)downFileWithOption:(NSDictionary *)paramDic withInferface:(NSString*)dourl andBlock:(void (^)(BOOL isSuccess, NSError *error))block
{
    NSString *serverUrlPrefix = [NSString stringWithFormat:@"%@%@",SERVER_BASICE_URL,dourl];
    NSURL *requestUrl = [NSURL URLWithString:serverUrlPrefix];
  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl];
    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    
    NSString *parameterString= [NSString string];
    parameterString = [parameterString jsonFromDictionay:paramDic];
    NSDictionary *paramaterDic=[NSDictionary dictionaryWithObject:parameterString forKey:@"jsonString"];
    
    NSLog(@"request url = %@",dourl);
    NSLog(@"paramaterDic = %@",serverUrlPrefix);
    
    //获取沙盒路径  //自定义的方法 需要自己修改
    NSString *savePath = [[Util applicationDocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",[paramDic objectForKey:@"filename"]]];
    
    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(paramaterDic, NSUTF8StringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savePath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        NSLog(@"is download:%f", (float)totalBytesRead / totalBytesExpectedToRead);
        
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        block(YES, nil);
        NSLog(@"下载成功");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        block(NO, error);
        NSLog(@"下载失败");
        
    }];
    
    [operation start];
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多