0
+ (NSString *) simpleAuth {

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


}];

return accessToken

}

trying to get my instagram accesstoken as a string so I can use it to download data in my swift viewcontroller file. I had to write simple auth in Objective C since it doesn't work for swift atm.

4

2 回答 2

4

由于该方法是异步运行的,因此您不能像那样返回访问令牌。我建议您在您的 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);
}];
于 2014-10-23T10:39:10.767 回答
0

不可能从响应块中“返回”对象。这是因为响应块是异步运行的,因此您的代码会在 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
}

在添加的完成块中:

[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationIdentifier" object: accessToken];
于 2014-10-23T10:36:26.290 回答