1

我需要下载经过身份验证的文件。我在 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获取文件?

4

1 回答 1

3

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

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

-requestWithMethod:URLString:parameters:error:返回一个NSMutableURLRequest你可以提供给NSURLSession's-downloadTaskWithRequest:或变体的。

希望这能给你你所需要的。

于 2014-01-15T10:52:28.620 回答