0

我正在尝试在我的应用程序后台仅使用本机代码将文件发布到 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
        }
    }];
}
4

1 回答 1

1

仅使用本机 Objective-C 代码是否有更简洁的方法来实现这一点?

不,这就是你的做法。您可以通过将部分逻辑封装到单独的方法中来使其看起来更清晰。您还有一些可以删除的冗长内容。(为什么使用[NSData dataWithData:image]而不是image?为什么maxConcurrentOperationCount只添加一个操作时设置?)

于 2013-10-29T15:36:35.397 回答