要求用户的权限使用本地通知

时间:2014-06-13 20:18:21

标签: ios notifications

我有一个警报,显示应用首次启动时,询问用户是否允许该应用发送本地通知。我在AppDelegate.m中有。警报没问题,但我在代码中有一个错误,用于测试按下了哪个按钮(是或否)。

我在- (void)alertView:clickedButtonAtIndex:行显示错误使用未声明的标识符 alertview

以下是代码:

//ask user if its ok to send local notifications
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Notifications?"
                                                  message:@"Is it ok for this app to send you reminder notifications? (You can change this in Settings)"
                                                 delegate:self
                                        cancelButtonTitle:@"No"
                                        otherButtonTitles:@"Yes", nil];
[message show];

//which button was clicked?
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [UIAlertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"No"])
    {
        NSLog(@"NO was selected.");
        [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"notifications"]; //0 = off, 1 = on
    }
    else
    {
        NSLog(@"YES was selected.");
        [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"notifications"]; //0 = off, 1 = on
    }    
}

1 个答案:

答案 0 :(得分:2)

替换行:

NSString *title = [UIAlertView buttonTitleAtIndex:buttonIndex];

使用:

NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

UIAlertView类没有类方法buttonTitleAtIndex:。这是一个实例方法,应该在UIAlertView类的实例上调用。

如果您想使用UIAlertViewDelegate方法,请确保符合alertView:clickedButtonAtIndex:协议。

修改

就像@Sam建议你也可以使用buttonIndex代替按钮标题,如果你不更新if语句,将来可以更改按钮标题。 p>

实施例

if (buttonIndex == 1) {
    // do something
} else {
    // do something else
}

编辑2

确保在方法定义之前有一个右括号“}”。

实施例

- (void)someMethod
{
    ...
}  <= DONT FORGET TO TYPE A CLOSING BRACKET 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex    
{
    ...
}