【问题标题】:Trying to return a string from a response object inside a completion handler [duplicate]尝试从完成处理程序中的响应对象返回字符串[重复]
【发布时间】:2014-10-23 10:15:34
【问题描述】:
+ (NSString *) simpleAuth {

[SimpleAuth authorize:@"instagram" completion:^(NSDictionary *responseObject, NSError *error) {
    NSLog(@"plump: %@", responseObject);
    NSString *accessToken = responseObject[@"credentials"][@"token"];


}];

return accessToken

}

尝试将我的 instagram 访问令牌作为字符串获取,以便我可以使用它在我的 swift viewcontroller 文件中下载数据。我不得不在 Objective C 中编写简单的身份验证,因为它不适用于 swift atm。

【问题讨论】:

  • 你不能这样做,你必须通知你的控制器你终于得到了令牌。使用通知或委托

标签: ios objective-c methods instagram completionhandler


【解决方案1】:

由于该方法是异步运行的,因此您不能就这样返回访问令牌。我建议您在您的 simpleAuth: 方法中添加一个完成块,该方法在获取访问令牌时将访问令牌传递给被调用者。

这样的方法会更好,

+ (void)simpleAuth:(void(^)(NSString*))completionHandler
{
  [SimpleAuth authorize:@"instagram" completion:^(NSDictionary *responseObject, NSError *error)   {
    NSString *accessToken = responseObject[@"credentials"][@"token"];
    completionHandler(accessToken)
  }];
} 

这样你会这样称呼它,

[SomeClass simpleAuth:^(NSString *accessToken){
  NSLog(@"Received access token: %@", accessToken);
}];

【讨论】:

    【解决方案2】:

    无法从响应块中“返回”对象。这是因为响应块是异步运行的,因此您的代码会在 Auth 调用之外继续运行。

    要解决这个问题,您可以使用委托或使用 NSNotifications。 NSNotifications 的示例是:

    在监听控制器中添加如下内容:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(authCompleted:)
                                                     name:@"NotificationIdentifier"
                                                   object:nil];
    

    听法:

    -(void)authCompleted:(NSNotification *)notification {
        NSString *accessToken = [notification object];
        //now continue your operations, like loading the profile, etc
    }
    

    并且在add的完成块中:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationIdentifier" object: accessToken];
    

    【讨论】:

    • 谢谢,我都试过了,但遇到了麻烦......最终通过 NSUserdefaults 存储,然后我可以在我的 swift 文件中访问它。
    • 很高兴听到您找到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多