我从不使用网络API,也不知道我对此有何看法。我阅读了FAROO Return Values doc,但我不明白我如何在cocoa中获得结果数组(或字典)。 请有人给我示例或教程如何在objective-c中使用Faroo API(或其他Web API)。
谢谢。
答案 0 :(得分: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];
}
答案 1 :(得分:-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