我需要在两个搜索引擎中实现同步搜索。我有两个功能: * - (void)searchYoutube:(NSString )text 和 * - (void)searchYahoo:(NSString )text
(void) searchYahoo:(NSString *)text{
NSString *urlString = [NSString stringWithFormat:@"http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=%@&output=json&query=%@&results=30", YahooAppId, text];
NSLog(@"URL zaprosa: %@",urlString);
//Create NSURL string from formatted string
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (connection)
{
NSLog(@"Data will be received from URL: %@", url);
}
else
{
NSLog(@"Data couldn't be received from URL: %@", url);
}}
功能-searchYoutube:与上面类似。但是当我用这两个函数调用查询时,我看到了
2011-06-26 14:06:27.523 TrueSearcher[5373:207] URL query: http://gdata.youtube.com/feeds/api/videos?q=os&start-index=1&max-results=30&alt=jsonc&v=2
2011-06-26 14:06:27.874 TrueSearcher[5373:207] Data will be received from URL: http://gdata.youtube.com/feeds/api/videos?q=os&start-index=1&max-results=30&alt=jsonc&v=2
2011-06-26 14:06:27.875 TrueSearcher[5373:207] URL query: http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=jwGJkT32&output=json&query=os&results=30
2011-06-26 14:06:29.010 TrueSearcher[5373:207] Data will be received from URL: http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=jwGJkT32&output=json&query=os&results=30
就是这样。我收不到任何数据。我做错了什么?
答案 0 :(得分:1)
好吧,
NSURLConnection *connection = [NSURLConnection
sendSynchronousRequest:request returningResponse:nil error:nil];
错了。 sendSynchronousRequest
会返回带有响应数据的(NSData *)
。所以,一个更正确的方法来做你想要的是
NSData *responseData = [NSURLConnection
sendSynchronousRequest:request returningResponse:nil error:nil];
然后您阅读responseData
的回复。
您还应该查看NSURLConnection的文档。
答案 1 :(得分:0)
这不是答案,而是提高绩效的建议,答案已经由uvesten提供。
sendSynchronousRequest不是一种好的实现方式,它不会在请求完成之前离开控件,所以如果加载需要时间,app就不会响应触摸。
相反,您可以尝试
NSString *urlString = [NSString stringWithFormat:@"http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=%@&output=json&query=%@&results=30", YahooAppId, text];
NSLog(@"URL zaprosa: %@",urlString);
//Create NSURL string from formatted string
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
并实现委托方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
expectedSize = [response expectedContentLength];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if (objData==nil) {
objData = [[NSMutableData alloc] init];
}
[objData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
}