如何在iOS目标c中发送带有多部分表单数据的put请求?

时间:2016-11-24 08:02:49

标签: ios objective-c

想要发送包含图像和字符串数据的put请求。这是我的代码供进一步参考。

+(void)uploadProfileImage:(NSData*)imageData forDeviceNumber:    (NSString*)number withDelegate:(id)delegate{

   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [[NSUserDefaults standardUserDefaults] setObject:@"Profile Image Upload" forKey:@"WHARRU_CALLED_API"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
    [SharableClass addLogForAPI:@"Profile Image Upload" withtimeStamp:[dateFormatter stringFromDate:[NSDate date]] message:@"API Called." withDelegate:delegate];
    [[NSUserDefaults standardUserDefaults] synchronize];


    NSString *parameter = @"\{\"deviceId\" : \"919555347279\", \"name\" : \"intervention\", \"emergencyContacts\" : \"10046\", \"photo\" : \"10046\"}"; // The rest of your parmas here

    ////////////////////////////////////////////////////

    NSString *registeredServer = [SharableClass getDataFromDBForKey:@"server"];
    NSString *APIURL = @"/api/updateProfile/updateImage";
    NSString *urlString = [NSString stringWithFormat:@"%@%@", registeredServer, APIURL];
    NSLog(@"\n\nURL String\n%@\n\n", urlString);
    NSURL *url = [NSURL URLWithString:urlString];

    NSString *urlString2 = @"img/logo.png";
    NSData* file =  [NSData dataWithContentsOfFile: [urlString2 stringByExpandingTildeInPath]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    [request setHTTPMethod:@"PUT"];
    [request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    NSMutableData *putData = [NSMutableData data];
    [request setHTTPBody:[parameter dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *jsonData = [parameter dataUsingEncoding:NSUTF8StringEncoding];
    [putData appendData:[NSData dataWithData:jsonData]];
    [putData appendData:[NSData dataWithData:file]];
    [request setHTTPBody:putData];


    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
        if([data length] >0 && error == nil){
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
            [SharableClass addLogForAPI:@"Profile Image Upload" withtimeStamp:[dateFormatter stringFromDate:[NSDate date]] message:@"API Success." withDelegate:delegate];
            __block NSError *error1;
            __block NSMutableDictionary *resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
            NSLog(@"Result Dictionary-: %@", resultsDictionary);
        }else if([data length] == 0 && error == nil){
            NSLog(@"There is no data.");
        }else if(error != nil){
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
            [SharableClass addLogForAPI:@"Profile Image Upload" withtimeStamp:[dateFormatter stringFromDate:[NSDate date]] message:@"API Failed." withDelegate:delegate];
            NSString * response = [NSString stringWithFormat:@"Result dictionary is-: %@", error];
            NSString *subStr = [SharableClass getSubsrtring:response betweenString:@"\""and:@"\""];
            NSLog(@"Error-: %@", subStr);
        }
    }];
});
}

1 个答案:

答案 0 :(得分:0)

我建议您使用AFNetworking框架,因为它简化了与您的网络请求相关的所有内容。

更确切地说,它有一个PUT方法:

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
      parameters:(id)parameters
      success:(void (^)(AFHTTPRequestOperation *operation, id  responseObject))success 
      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

修改 请改用此方法(如本回答https://stackoverflow.com/a/30388087/1420112中所述):

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSError *error;
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSString *value = @"qux";
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
    [formData appendPartWithFormData:data name:@"baz"];
} error:&error];

NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (error) {
        NSLog(@"%@", error);
        return;
    }

    NSLog(@"%@", responseObject);
}];
[task resume];

请在此处查看:https://github.com/AFNetworking/AFNetworking