Reputation: 16186
I need to download files that are authenticated. I have this in the python side:
@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
This work fine when use the python request library / browser.
Then I have this in 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);
}];
The request pass, but the responseObject is nil
.
So I try with:
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];
This is a lot of repetition. So:
1) Is possible to use NSURLSessionDownloadTask and be able to send the params as with self.session POST
?
2) Or self.session POST
and get the file?
Upvotes: 1
Views: 1208
Reputation: 7386
AFHTTPSessionManager
exposes a requestSerializer
property, by default a AFHTTPRequestSerializer
instance.
AFHTTPRequestSerializer
in turn provides -requestWithMethod:URLString:parameters:error:
.
-requestWithMethod:URLString:parameters:error:
returns an NSMutableURLRequest
that you can feed to NSURLSession
's -downloadTaskWithRequest:
, or variations.
Hopefully that gives you what you need.
Upvotes: 3