如何使用 NSXML 解析 Google 天气 API?

发布于 2024-09-10 21:31:36 字数 1644 浏览 5 评论 0原文

我想使用 NSXML 解析 google 天气 API,所以请给我一些指导。

这是我的网址

,我已经采取了这样的步骤:

NSURL *url = [NSURL URLWithString:@"http://www.google.com/ig/api?weather=Ahemdabad"];

 NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
 [theRequest setHTTPMethod:@"POST"];
 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

 if(theConnection){
  webData = [[NSMutableData data] retain];
  NSLog( @"connection established");
 }
 else {
  NSLog(@"theConnection is NULL");
 }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
 [webData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [webData appendData:data]; 
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
 NSLog(@"ERROR with theConenction");
 [connection release];
 [webData release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connectio   
{     
    NSLog(@"DONE. Received Bytes: %d", [webData length]);

 NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
 NSLog(@"thexml=============>%@", theXML);
 [theXML release];


 if(parser)
 {
  [parser release];
 }

 parser = [[NSXMLParser alloc]initWithData:webData];
 [parser setDelegate: self];
 [parser setShouldResolveExternalEntities: YES];
 [parser parse];

 [connection release];
 [webData release];

}

i want to parse google weather API using NSXML so please give me some Guidance for this.

This is My url

and i have taken such kind of steps:

NSURL *url = [NSURL URLWithString:@"http://www.google.com/ig/api?weather=Ahemdabad"];

 NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
 [theRequest setHTTPMethod:@"POST"];
 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

 if(theConnection){
  webData = [[NSMutableData data] retain];
  NSLog( @"connection established");
 }
 else {
  NSLog(@"theConnection is NULL");
 }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
 [webData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [webData appendData:data]; 
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
 NSLog(@"ERROR with theConenction");
 [connection release];
 [webData release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connectio   
{     
    NSLog(@"DONE. Received Bytes: %d", [webData length]);

 NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
 NSLog(@"thexml=============>%@", theXML);
 [theXML release];


 if(parser)
 {
  [parser release];
 }

 parser = [[NSXMLParser alloc]initWithData:webData];
 [parser setDelegate: self];
 [parser setShouldResolveExternalEntities: YES];
 [parser parse];

 [connection release];
 [webData release];

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥繁 2024-09-17 21:31:36

嘿 ankit,如果对您有帮助,您可以获取此代码,无需建立连接,

只需使用此方法即可

-(id)initWithURL:(NSURL*)url arrayRootObjectTags:(NSArray*)arrTags sel:(SEL)seletor andHandler:(NSObject*)handler{
    if(self = [super init] ){
        self.mainArray=arrTags;
        self.MainHandler=handler;
        self.targetSelector=seletor;
        NSLog(@"%@",[url description]);
        NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:30];                 
        con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
        if(con){
            myWebData=[[NSMutableData data] retain];
        } else {
            [MainHandler performSelector:@selector(targetSelector:) withObject:nil];
        }
    }
    return self;
}

,也可以使用其他支持方法

-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict {
    if([elementName isEqualToString:@"html"] || [elementName isEqualToString:@"HTML"]){
        didGetHTML=YES; [self parserDidEndDocument:parser];
    } else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML) {
        objectsArray=[[NSMutableArray alloc] init];
        tmpD=[[NSMutableDictionary alloc] init];
        if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];      
    } else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && !didGetHTML ) {
        objectsArray=[[NSMutableArray alloc] init];
        if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];      
    } else if([[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML ) {
        tmpD=[[NSMutableDictionary alloc] init];
    } else if([mainArray containsObject:elementName] && !didGetHTML){
        [tmpD setValue:[attributeDict valueForKey:@"data"] forKey:elementName];
    }
}

-(void)parser:(NSXMLParser*)parserfoundCharacters:(NSString*)string {
if(tmpString==nil && !didGetHTML){
tmpString=[[NSString alloc] initWithString:string];
} 否则 if(!didGetHTML){
NSString *t=[NSString stringWithString:tmpString];
if([tmpString keepCount]>0) { [tmpString release]; tmpString=nil; }
tmpString=[[NSString alloc] initWithFormat:@"%@%@",t,string];
}

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
    if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML){
        [objectsArray addObject:tmpD];
    } else if([elementName isEqualToString:[mainArray objectAtIndex:1]] && !didGetHTML){
        [objectsArray addObject:tmpD];
        [tmpD release]; tmpD=nil;
    } else if([mainArray containsObject:elementName] && !didGetHTML) {
        if(![tmpD valueForKey:elementName]){
            [tmpD setValue:tmpString forKey:elementName];
        }
        [tmpString release]; tmpString=nil;     
    } else {
        [tmpOther setValue:tmpString forKey:elementName];
        [tmpString release]; tmpString=nil;
    }
}

简单地从您编写此方法的类中调用 initwith url 方法,

只需提供根标记对象标记和特定对象标记的元素标记,并在之后提供选择器,然后在字典中获取响应,然后将其接收数组并根据您的键值显示结果

hey ankit you can get this code if at all its helpful to you no need to establish connection

just use this method

-(id)initWithURL:(NSURL*)url arrayRootObjectTags:(NSArray*)arrTags sel:(SEL)seletor andHandler:(NSObject*)handler{
    if(self = [super init] ){
        self.mainArray=arrTags;
        self.MainHandler=handler;
        self.targetSelector=seletor;
        NSLog(@"%@",[url description]);
        NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:30];                 
        con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
        if(con){
            myWebData=[[NSMutableData data] retain];
        } else {
            [MainHandler performSelector:@selector(targetSelector:) withObject:nil];
        }
    }
    return self;
}

also the other supporting method

-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict {
    if([elementName isEqualToString:@"html"] || [elementName isEqualToString:@"HTML"]){
        didGetHTML=YES; [self parserDidEndDocument:parser];
    } else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML) {
        objectsArray=[[NSMutableArray alloc] init];
        tmpD=[[NSMutableDictionary alloc] init];
        if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];      
    } else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && !didGetHTML ) {
        objectsArray=[[NSMutableArray alloc] init];
        if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];      
    } else if([[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML ) {
        tmpD=[[NSMutableDictionary alloc] init];
    } else if([mainArray containsObject:elementName] && !didGetHTML){
        [tmpD setValue:[attributeDict valueForKey:@"data"] forKey:elementName];
    }
}

-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string {
if(tmpString==nil && !didGetHTML){
tmpString=[[NSString alloc] initWithString:string];
} else if(!didGetHTML){
NSString *t=[NSString stringWithString:tmpString];
if([tmpString retainCount]>0) { [tmpString release]; tmpString=nil; }
tmpString=[[NSString alloc] initWithFormat:@"%@%@",t,string];
}
}

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
    if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML){
        [objectsArray addObject:tmpD];
    } else if([elementName isEqualToString:[mainArray objectAtIndex:1]] && !didGetHTML){
        [objectsArray addObject:tmpD];
        [tmpD release]; tmpD=nil;
    } else if([mainArray containsObject:elementName] && !didGetHTML) {
        if(![tmpD valueForKey:elementName]){
            [tmpD setValue:tmpString forKey:elementName];
        }
        [tmpString release]; tmpString=nil;     
    } else {
        [tmpOther setValue:tmpString forKey:elementName];
        [tmpString release]; tmpString=nil;
    }
}

and simply call the initwith url method from which ever class you have written this method

just you have to give root tag object tag and element tag of a particular object tag and also give selector after that take the response in dictionary and they take it in array and display the result according to your value for key

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文