OGeek|极客世界-中国程序员成长平台

标题: ios - 在异步 REST 请求的 block 内调用 self [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:35
标题: ios - 在异步 REST 请求的 block 内调用 self

[self userLoggedIn]withBlock block 内时,我无法调用它。它被调用但不显示 TITHomeViewController。如果我将它移到 block 的下方和外部,那么它可以正常工作。显然,我希望从 withBlock 中调用它,因为它是异步 REST 请求的完成处理程序。

- (void)doAuth
{
    // Call the Facebook API /me method
    [FBRequestConnection startForMeWithCompletionHandler:
     ^(FBRequestConnection *connection, id result, NSError *error)
     {
         // Populate global Facebook user info
         self.fbAccessToken = [[[FBSession activeSession] accessTokenData] accessToken];
         self.fbUserID = [result objectForKey"id"];

         // Authenticate with the Titter API
         [self callAPI"auth" withBlock:^(NSDictionary *jsonData) {
             NSString *_id = [jsonData objectForKey"_id"];
             if (_id != nil) {
                 self.userID = _id;
                 [self userLoggedIn];
             }
         }];
     }];
}

- (void)userLoggedIn
{
    // Display the home view.
    self.window.rootViewController = [[TITHomeViewController alloc] initWithNibName"TITHomeViewController" bundle:nil];
}

- (void)callAPINSString *)path withBlockvoid (^)(NSDictionary *jsonData))block
{
    // Initialize the API callback URL using global root and given path
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat"%@%@", apiRoot, path]];

    // The Titter API requires an authorization header formatted as [userID]@[accessToken]
    NSString *authorizationHeader = [NSString stringWithFormat"%@@%@", self.fbUserID, self.fbAccessToken];

    // Create the request and add our authorization header
    NSMutableURLRequest *restRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    [restRequest addValue:authorizationHeader forHTTPHeaderField"authorization"];

    // Queue required for calling sendAsynchronousRequest
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    // Make an asynchronous request to our API and if there is no errors, return formatted JSON data to the passed block.
    [NSURLConnection
     sendAsynchronousRequest:restRequest
     queue: queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) {
         if ([data length] >0 && error == nil) {
             NSLog(@"Succeeded! Data as string: %@", [NSString stringWithUTF8String:[data bytes]]);

             // Convert received JSON data into a NSDictonary object.
             NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

             // Call back the block passed in.
             block(result);
         }
         else if ([data length] == 0 && error == nil) {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil) {
             NSLog(@"Error = %@", error);
         }
     }];
}



Best Answer-推荐答案


上面的评论线程让您完成了大约 90% 的任务! UI 在主线程上运行,对其的任何更新都应在 UI 线程上进行。您可以通过在主线程上调用 usedLoggedIn 在 block 代码中修复此问题:

dispatch_async(dispatch_get_main_queue(), ^{
  [self userLoggedIn];
});

还值得注意的是,您可能在 block 内使用 self 时遇到问题:如果 self 消失,该 block 将失败。在此用例中,这可能不是问题。您没有提及此代码来自哪个类:如果它来自 View Controller ,则可以安全地假设它不会去任何地方。但是,如果它是一个辅助对象或类似的东西,它可能会在请求 URL 时从您下方消失(或在该逻辑中的某个位置)。通常的做法是创建对 self 的弱引用以在 block 内使用,如下所示:

// Outside the block
MyViewController __weak *weakSelf = self;

// Inside the block
[weakSelf userLoggedIn];

关于ios - 在异步 REST 请求的 block 内调用 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23372265/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4