将NSData添加到NSDirectory(JSON)中,在JSON写入(NSConcreteMutableData)错误中获取无效类型

时间:2013-03-26 06:51:37

标签: ios afnetworking

我正在尝试将Image添加到我想要在服务器上发布的JSON文件中。我使用以下代码,但我一直收到Invalid type in JSON write (NSConcreteMutableData)错误。代码是

NSDictionary *parameter = [[NSDictionary alloc]init];
NSData *imageData = UIImagePNGRepresentation(imageView.image);
parameter = @{@"body":@"Hi",@"image":imageData};

另外,我正在使用AFNetworking将图片发布到服务器

我不确定代码中有什么问题。任何帮助都将受到高度赞赏

2 个答案:

答案 0 :(得分:3)

如果其他人以后遇到同样的问题。这是您应该使用的代码

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSDictionary *parameter = @{@"body":@"image"};
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:parameter constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

来源:link

答案 1 :(得分:1)

尝试这样,

parameter = @{@"body":@"Hi",@"image":[NSString stringWithFormat:@"%@" ,imageData]};