如何在AFNetworking 2中使用POST + params下载经过身份验证的文件?

时间:2014-01-13 22:45:49

标签: afnetworking-2 nsurlsessiondownloadtask

我需要下载经过身份验证的文件。我在python方面有这个:

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    schema = request.user.company.username
    db = dbSync(schema)

    filePath = db.dbPath()

    tables = [(db.getTable('location'), 0)]

    if db.copyTables(filePath, tables):
        wrapper = FileWrapper(file(filePath))
        response = HttpResponse(wrapper, content_type='application/x-sqlite3')
        response['Content-Length'] = os.path.getsize(filePath)
        response['Content-Disposition'] = 'attachment; filename="tables.db"'
        response['Content-Transfer-Encoding'] = 'binary'
    else:
        response = HttpResponseNotModified()

    return response

使用python请求库/浏览器时,此工作正常。

然后我在iOS中有这个:

[self.session POST:@"sync/tables/" parameters:tables
           success:^(NSURLSessionDataTask *task, id responseObject) {
               DDLogInfo(@"%@", responseObject);
               handler(nil);
           }
           failure:^(NSURLSessionDataTask *task, NSError *error) {
               DDLogCError(@"%@",error);

              handler(error);
           }];

请求传递,但responseObject为nil

所以我尝试:

NSURL *URL = [NSURL URLWithString:@"http://localhost:8000/sync/tables/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

    [request setValue:self.token forHTTPHeaderField:@"AUTHORIZATION"];
    [request setHTTPMethod:@"POST"];

    NSMutableString *params = [NSMutableString string];

    [tables enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [params appendFormat:@"%@=%@", key, obj];
    }];

    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.db"];

        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        DDLogInfo(@"File downloaded to: %@", filePath);

        if (error) {
            DDLogError(@"%@", error);
        }
        handler(error);
    }];
    [downloadTask resume];

这是很多重复。所以:

1)是否可以使用NSURLSessionDownloadTask并且能够像self.session POST一样发送参数?

2)或self.session POST并获取文件?

1 个答案:

答案 0 :(得分:3)

AFHTTPSessionManager公开requestSerializer属性,默认情况下为AFHTTPRequestSerializer个实例。

AFHTTPRequestSerializer反过来提供-requestWithMethod:URLString:parameters:error:

-requestWithMethod:URLString:parameters:error:会返回NSMutableURLRequest,您可以将NSURLSession的{​​{1}}或其变体提供给-downloadTaskWithRequest:

希望能为您提供所需的产品。