我编写了GET方法代码以从服务器(json格式)检索详细信息。但是我收到错误(操作无法完成)。 谁能请我提供一些有关此事的信息? 我的代码:
-(void)getResponseWithOutBodywithMethod:(NSString*)method
{
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:method];
//[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [request setTimeoutInterval:20.0];
NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData alloc] init] ;
}
}
#pragma mark NSURLConnection delegate methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response{
/* This method is called when the server has determined that it has
enough information to create the NSURLResponse. It can be called
multiple times, for example in the case of a redirect, so each time
we reset the data. */
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData: ( NSData *)data{
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:( NSError *)error{
completion(nil, error);
NSLog(@"%@",[error localizedDescription]);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
if (receivedData != nil) {
NSError *jsonParsingError = nil;
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData
options:kNilOptions error:&jsonParsingError];
NSString* str = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"error %@",jsonParsingError.localizedDescription);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"ER" message:str delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
if (dict == nil && [dict count]==0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:jsonParsingError.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
completion(nil, jsonParsingError);
}
else {
completion(dict, nil);
}
}
else {
completion(nil, [NSError errorWithDomain:@"http" code:-1 userInfo:nil]); //todo proper error
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to get data." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}
答案 0 :(得分:0)
好吧,我认为你的Json就是问题所在。
如果您的服务器正在响应:
东西= somethingelse
这不是正确的格式。您需要对Json进行编码,使其看起来像:
[{“key”:“value”,“key”:“value”}]