iOS日常bug

AFNetWorking 崩溃问题

2017-05-25  本文已影响294人  沙窝田

1)crash的位置:

报错信息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

*** First throw call stack:

解决办法:网络请求时候的参数是string类型,应该改为dictionary或者json类型

如果后台参数必须是string类型,就要改afnetworking的源码,

在afnetworkng的源码中找到这个方法,然后用下面的代码把这个方法替换掉。

替换为:

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request

withParameters:(id)parameters

error:(NSError *__autoreleasing *)error

{

NSParameterAssert(request);

if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {

return [super requestBySerializingRequest:request withParameters:parameters error:error];

}

NSMutableURLRequest *mutableRequest = [request mutableCopy];

[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {

if (![request valueForHTTPHeaderField:field]) {

[mutableRequest setValue:value forHTTPHeaderField:field];

}

}];

if (parameters) {

if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {

[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

}

#pragma mark - alter by huangzhikai针对请求参数无key的情况

if ([parameters isKindOfClass:[NSString class]]) {

NSData *strData =[parameters dataUsingEncoding:NSUTF8StringEncoding];

[mutableRequest setHTTPBody:strData];

}

else{

[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];

}

//[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];

}

return mutableRequest;

}

上一篇下一篇

猜你喜欢

热点阅读