如何在没有外部库的情况下将文件干净地POST到API端点?

时间:2013-10-29 15:27:42

标签: ios objective-c rest

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

1 个答案:

答案 0 :(得分:1)

  

有没有更简洁的方法来实现这一点,只使用原生   Objective-C代码?

不,你就是这样做的。您可以通过将逻辑的一部分封装到单独的方法中来使其看起来更干净。你也有一些可以删除的冗长的东西。 (为什么使用[NSData dataWithData:image]代替image?为什么在仅添加一项操作时设置maxConcurrentOperationCount?)