0

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

谢谢你。

4

2 回答 2

0

要特别使用 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];
}
于 2013-09-19T08:25:47.027 回答
-1

另一种做事方式是自己将缺失的方法声明为相关类的一个类别。这将使编译器停止抱怨找不到该方法,当然您仍然需要您已经在执行的运行时检查以避免实际调用该方法。您可能还想使用可用性宏来包装这样的声明,以便在您升级到使用 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
于 2013-09-14T05:09:04.093 回答