ios - UIAlertView 在完成处理程序 block 中不起作用

标签 ios objective-c

我正在编写代码以获取对用户 Twitter 帐户的访问权限,但在处理设备上没有帐户的情况时遇到了问题。我想要做的是显示一个警告,告诉用户为了通过 Twitter 进行身份验证,他们首先需要在他们的设置中创建帐户。

这是我的代码:

self.accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeTwitter = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

[self.accountStore requestAccessToAccountsWithType:accountTypeTwitter options:nil completion:^(BOOL granted, NSError *error) {
    if(granted) {
        //Doesn't matter for the present case
    } else if (error){

        [SVProgressHUD dismiss]; //not directly relevant to the present question, but it also doesn't work within the block, so I'm leaving it as a clue

        switch ([error code]){
            case (6):

                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No Twitter Account Detected" message:@"Please go into your device's settings menu to add your Twitter account." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show]; //triggers an error
                break;

        }
    } 
}];

我不是 Xcode 调试器方面的专家,但显然错误发生在 ACAccountStoreReply 线程中,在调用 [alert show] 之后大约 25 次深度调用,在一个名为 ucol_getVersion 的进程中。调试器状态为 EXC_BAD_ACCESS(代码=2,地址=0xcc)。

我在 Stack Overflow 和整个互联网上搜索了有关 UIAlertViews 无法成 block 工作的解决方案,还搜索了显示警报的一般问题(我为委托(delegate)尝试了不同的值),以及调用的一般问题请求AccessToAccountsWithType。

我还尝试通过阅读各种在线资源和《Objective-C 编程,第 4 次补充》的相关页面来温习我对 block 的理解。

感谢任何帮助。

最佳答案

您应该始终确保任何 UI 交互都在主线程上完成。将您的 UIAlertView 调用包装在 dispatch_async 中:

dispatch_async(dispatch_get_main_queue(), ^{
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Twitter Account Detected" message:@"Please go into your device's settings menu to add your Twitter account." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
});

您在调用结束时还有两个 nil

关于ios - UIAlertView 在完成处理程序 block 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056740/

相关文章:

iphone - 我的按钮上有阴影

ios - viewDidDisappear 时布局被破坏

ios - 所有目标的 FaSTLane increment_build_number?

ios - Interface Builder 中的自定义字体

iphone - iOS7自定义按钮高亮时变透明

ios - 停止播放系统声音

iphone - 对于复制 NSString,我是否需要显式保留副本

iphone - 使用 View Controller 包含, child 失去 parent

ios - 今天扩展中复制的主要应用程序 Assets 目录

ios - 如何将数据从一个 View 传递到下一个 View ?