新しいバックグラウンド セッション アップロードを利用するために、AFNetworking 3.0 を使用して追加情報 (私の場合はcaption
& ) を含むディスクからのアップロード ファイルをどのように実装しますか?channel_id
uploadTaskWithRequest:fromFile:progress:completionHandler
AFNetworking とバックグラウンド ファイルのアップロードで動作する場合は、代替ソリューションを受け入れます。
これは、サーバーが400の不正なリクエストまたは500の内部処理エラーで応答することを試したものです(cURLでマルチパートフォームの投稿を行うと機能します):
@property (nonatomic, strong) AFURLSessionManager *uploadSession;
// Configured uploadSession as backgroundSession configuration with couple of headers
- (void)uploadMediafileFilename:(NSString *)filename
filenameWithPath:(NSString *)filenameWithPath
progress:(void ( ^ ) ( NSProgress *uploadProgress ))progress
caption:(NSString *)caption
channel:(NSString *)channelId
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
// ---------
// Create Request Method #1
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@/", kAPIBaseURL, kAPIMediafilesURL]]];
// Tried dictionary to JSON in body. Also tried a params string version.
NSDictionary *dict = @{ @"channel_id" : channelId,
@"mediafile" : @{ @"filename" : filename, @"caption" : caption } };
request.HTTPBody = [NSKeyedArchiver archivedDataWithRootObject:dict];
request.HTTPMethod = @"POST";
// ---- OR ----
// Create Request Method #2
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@", kAPIBaseURL, kAPIMediafilesURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:[caption dataUsingEncoding:NSUTF8StringEncoding] name:@"mediafile[caption]"];
[formData appendPartWithFormData:[channelId dataUsingEncoding:NSUTF8StringEncoding] name:@"channel_id"];
[formData appendPartWithFileURL:fileURL name:@"mediafile[filename]" fileName:filename mimeType:@"image/jpeg" error:nil];
} error:nil];
// ----------
NSURL *fileURL = [NSURL fileURLWithPath:filenameWithPath];
[request setValue:[self token] forHTTPHeaderField:kTokenHeaderField];
// Tried using uploadTaskWithRequest - prefer due to its background capabilities. Also tried uploadTaskWithStreamedRequest.
NSURLSessionUploadTask *uploadTask = [self.uploadSession uploadTaskWithRequest:request fromFile:fileURL progress:progress completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", [response description]);
}
if (completionBlock) {
completionBlock(response, responseObject, error);
}
}];
[uploadTask resume];
}