我有这个 RESTFUL API 调用。我尝试连接到 Web 服务。响应成功接收但是当我注销数据接收时,它没有。请帮我。我的休息信息错了吗?
这是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
feeds = [[NSMutableArray alloc] init];
NSString *restMessage = [NSString stringWithFormat:@"https://deepsightapi.symantec.com/v1/domains/www.google.com/"];
NSURL *url = [NSURL URLWithString:restMessage];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
//[connection start];
if(connection)
{
_webResponseData = [NSMutableData data] ;
}
else
{
NSLog(@"Connection is NULL");
}
}
- (void)connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Response recieved");
[self.webResponseData setLength:0];
}
- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
NSLog(@"Data recieved");
[self.webResponseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);
NSString *theXML = [[NSString alloc] initWithBytes:
[_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];
NSLog(@"hello %@",theXML);
//now parsing the xml
NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData];
//setting delegate of XML parser to self
xmlParser.delegate = self;
// Run the parser
@try{
BOOL parsingResult = [xmlParser parse];
NSLog(@"parsing result = %hhd",parsingResult);
}
@catch (NSException* exception)
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Server Error" message:[exception reason] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
return;
}
}
最佳答案
我用过这种方式,可以将你的响应转化为Dictionary或者Array。 请用下面给出的代码替换您的代码。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %d bytes of data",[_webResponseData length]);
NSString *responseText = [[NSString alloc] initWithData:_webResponseData encoding: NSASCIIStringEncoding];
NSLog(@"Response by server is : %@", responseText);
NSError *e;
// Convert into Array
NSMutableArray *object = [NSJSONSerialization JSONObjectWithData:_webResponseData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@",object[0]);
// Print your field
// Convert into Dictionary
NSMutableDictionary *objectDic = [NSJSONSerialization JSONObjectWithData:_webResponseData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@",objectDic[@"your Key name"]);
如果有效,请告诉我。 谢谢
关于IOS 如何使用 RESTFUL API 从 Web 服务中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34351199/