iOS:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'JSON写入中的类型无效(_NSInlineData)'

时间:2014-07-27 18:19:09

标签: ios json nsurlsession

NSData *imgData;
if (!_groupImageView.image)
{
    imgData=[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:@"Replay.png"])];
}
else
{
    imgData=[NSData dataWithData:UIImagePNGRepresentation(_groupImageView.image)];
}
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL* url = [NSURL URLWithString:[ NSString stringWithFormat:@"%@groups/create",[sharedObj getSiteUrl]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:sharedObj.acessToken, @"tocken",  _txtGroupName.text, @"name",imgData, @"image",  nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];

当我尝试对图像数据进行JSON编码时,我得到了这个异常,

  

由于未捕获的异常而终止应用   'NSInvalidArgumentException',原因:'JSON写入中的类型无效   (_NSInlineData)'

1 个答案:

答案 0 :(得分:4)

或者使用base64EncodedString将imgData更改为字符串;

NSData *imgData;
if (!_groupImageView.image)
{
    imgData=[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:@"Replay.png"])];
}
else
{
    imgData=[NSData dataWithData:UIImagePNGRepresentation(_groupImageView.image)];
}

//将图像数据更改为base64EncodedString

NSString *base64=[imgData base64EncodedStringWithOptions:0];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL* url = [NSURL URLWithString:[ NSString stringWithFormat:@"%@groups/create",[sharedObj getSiteUrl]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

//将base64添加为键"图像"

的值
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:sharedObj.acessToken, @"tocken",  _txtGroupName.text, @"name",base64, @"image",  nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];