我正在尝试在我的应用程序后台仅使用本机代码将文件发布到 API 端点。我可以使用以下代码,但这对我来说似乎非常笨拙。
仅使用本机 Objective-C 代码是否有更简洁的方法来实现这一点?
这是我尝试过的:
- (void)sendMyImage:(NSData *)image
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:true];
NSString *previewApiUrl = @"URL_OF_MY_ENDPOINT"]
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:previewApiUrl]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", @"MYFILENAME"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:image];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Include the auth headers
[request setValue:@"MYVALUE1" forHTTPHeaderField:@"CUSTOM_AUTH_HEADER_1"];
[request setValue:@"MYVALUE2" forHTTPHeaderField:@"CUSTOM_AUTH_HEADER_2"];
[request setHTTPBody:postbody];
NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) {
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:false];
if (!error) {
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; //parse my JSON response
}
else {
// Handle error condition
}
}];
}