我使用 Yelp 搜索 API 基本上只是获取用于搜索查询的企业列表。
NSURLConnection 几乎就是 OAuth,但这里是初始化请求的代码:
NSURL *URL = [NSURL URLWithString:appDelegate.yelpAdvancedURLString];
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:@"this-is-my-key" secret:@"this-is-my-secret"];
OAToken *token = [[OAToken alloc] initWithKey:@"this-is-my-key" secret:@"this-is-my-secret"];
id<OASignatureProviding, NSObject> provider = [[OAHMAC_SHA1SignatureProvider alloc] init];
NSString *realm = nil;
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:URL
consumer:consumer
token:token
realm:realm
signatureProvider:provider];
[request prepare];
responseData = [[NSMutableData alloc] init];
yelpConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
那么这里:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Error: %@, %@", [error localizedDescription], [error localizedFailureReason]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Oops." message: @"Something screwed up. Please search again." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.yelpConnection) {
[self setYelpString];
}
}
当我在 iPhone 上运行它时,一切正常。但是,当我在 iPad 上运行时,连接会超时。以下来自这一行
NSLog(@"Error: %@, %@", [error localizedDescription], [error localizedFailureReason]);
Error: The request timed out., (null)
另外,如果我使用同步请求,它似乎可以使用:
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary* JSON = [NSJSONSerialization
JSONObjectWithData:result
options:kNilOptions
error:&error];
但是,我想避免使用同步,因为它会冻结应用程序。
这个 Yelp API 是特定的吗?还是我只是做错了什么?在此先感谢,我将不胜感激。
如果有帮助,它会在发送请求后大约 10 秒超时。