如何在可可中使用Faroo搜索API



我从不使用Web API,也不知道我可能会读到什么。我阅读了 FAROO 返回值文档,但我不明白如何在可可中获得结果数组(或字典)。请任何人给我如何在objective-c中使用Faroo API(或其他Web API)的示例或教程。

谢谢。

要使用Web API和FAROO API,我特别使用NSURLConnection类和NSURLConnectionDelegate协议:

- (IBAction)search:(id)sender {
    NSString* requestString = [NSString stringWithFormat:@"http://www.faroo.com/api?q=%@&start=1&length=10&l=ru&src=news&f=xml&YOUR_API_KEY",[searchField stringValue]];
   // NSLog(@"str %@",requestString);
    NSURL* requestUrl = [NSURL URLWithString:requestString];
    NSURLRequest* searchRequest = [NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
    [self performSelectorOnMainThread:@selector(startConnectionWithRequest:) withObject:searchRequest waitUntilDone:NO];
}
- (void)startConnectionWithRequest:(NSURLRequest*)request {
    NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
    if (connection) {
      //update GUI and do something...
        theData = [NSMutableData data];
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"Receive data");
    [theData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@"Http status code %ld",(long)[httpResponse statusCode]);
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Finish");
    //do something with data and update GUI
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSAlert* searchFailedAlert = [NSAlert alertWithError:error];
    [searchFailedAlert runModal];
}

另一种方法是将缺少的方法声明为相关类的一个类别。这将使编译器停止抱怨找不到该方法,当然您仍然需要您已经在做的运行时检查以避免实际调用该方法。您可能还希望使用可用性宏包装此类声明,以便在升级到使用 10.5/10.6 SDK 后将其忽略,并且不会收到不同的编译器投诉。那看起来像这样:

#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4 //ignore when compiling with the 10.5 SDK or higher
@interface NSPropertyListSerialization(MissingMethods)
+ (NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(NSError **)error;
@end
#endif

最新更新