0

当我线程化我的代码时,我似乎无法让委托回调工作。我正在尝试使用 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];

}
4

2 回答 2

0

您是否放置了存根来实现所需的协议方法,

-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

因为我有一个类似的问题,在实施它们后就消失了。

于 2012-06-19T18:05:26.320 回答
0

因此,经过更多研究,我找到了解决方案。

我实际上并不需要 AccessToken.h/m。我认为 NSURLConnection 调用会阻塞我的 UI 线程。但是 NSURLConnection connectionWithRequest:delegate: 会自动在单独的线程中运行。

所以我所要做的就是删除 AccessToken.h 和 AccessToken.m。然后,在 CallingClass.m 中,我将 favourte: 更改为

- (IBAction)favourite:(id)sender 
{
    LoginViewController *loginViewController = [[LoginViewController alloc] init];
    [loginViewController fetchAccessTokenWithDelegate:self];

}

就是这样!根本不需要 dispatch_queue_t。

于 2012-06-20T18:55:09.833 回答