当我线程化我的代码时,我似乎无法让委托回调工作。我正在尝试使用 NSURLConnection 调用远程服务器以获取 access_token。access_token 在 connection:didReceiveResponse: delegate 中接收。在我穿线之前,这不是问题。我以为我为我的代表传递了正确的对象,但它没有达到连接:didReceiveResponse:
任何人都可以看到为什么在我线程调用时没有调用 LoginViewController 中的 connection:didReceiveResponse: 吗?谢谢。
登录视图控制器.m
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSString *access_token = [self getTokenFromResponse: response];
[self.delegate didGetAccessToken:access_token];
}
- (void)fetchAccessTokenNoUI
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: @"www.mysite.com"]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
访问令牌.h
@interface AccessToken : NSObject
@property (atomic, strong) LoginViewController *loginViewController; // doing this to try to keep it persistent
- (void) fetchAccessTokenWithDelegate: (id <LoginDelegate>)delegate;
@end
访问令牌.m
- (void) fetchAccessTokenWithDelegate: (id < LoginDelegate >)delegate
{
dispatch_queue_t downloadQueue = dispatch_queue_create("Fetch access_token queue", NULL);
dispatch_async(downloadQueue, ^ {
// this works fine if I don't do it in a queue
self.loginViewController = [[LoginViewController alloc] init];
self.loginViewController.delegate = delegate;
[self.loginViewController fetchAccessTokenNoUI];
});
dispatch_release(downloadQueue);
}
调用类.m
- (void)didGetAccessToken:(NSString *)access_token
{
if (!access_token)
{
LoginViewController *userProfileViewController = [[LoginViewController alloc] init];
userProfileViewController.delegate = self;
[self.navigationController pushViewController:userProfileViewController animated:YES];
}
}
- (IBAction)favourite:(id)sender
{
AccessToken *accessToken = [[AccessToken alloc] init];
[accessToken fetchAccessTokenWithDelegate:self];
}