您可以使用 NSURLConnection(或)Json 库来解析从服务器接收到的数据。
下面是使用 NSURL 连接解析 JSON 的示例代码:
在 viewDidLoad 中:
NSString *strConfirmChallenge = [URL string];
strConfirmChallenge = [strConfirmChallenge stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"strConfirmChallenge=%@",strConfirmChallenge);
NSURL *myURL = [NSURL URLWithString:strConfirmChallenge];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
//Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//NSLog(@"Failed to get data");
self.view.userInteractionEnabled = TRUE;
UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"Service error" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[myalert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
dispatch_async(kBgQue, ^{
[self performSelectorOnMainThread:@selector(parseData:)
withObject:responseData
waitUntilDone:YES];
});
self.view.userInteractionEnabled = TRUE;
}
//parsing data
-(void)parseData:(NSData *)data{
NSError *error;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:data options:(0) error:&error];
if(error){
//NSLog(@"JSon Error %@",[error localizedDescription]);
UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"Service error" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[myalert show];
}else{
NSDictionary *datDetails = (NSDictionary *) [data objectForKey:@"your key"];
}
}