oc本地推送

首先 我们先拖拽一个switch控件 并将其与 ViewController.m 关联,以方便我们以下的操作

1 我们现在 ViewController.m 中 为其设置一个全局变量并初始化

@interface ViewController ()
{
    UIApplication *app;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    app = [UIApplication sharedApplication];
}

2 我们在switch方法中写具体的代码

- (IBAction)changed:(id)sender
{
    UISwitch *sw = (UISwitch *)sender;
    if (sw.on)
    {
        if ([UIApplication instanceMethodForSelector:@selector(registerUserNotificationSettings:)])
        {
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
        }
        // 创建一个本地通知
        UILocalNotification *not = [[UILocalNotification alloc] init];
        // 设置触发时间
        not.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
        // 时区
        not.timeZone = [NSTimeZone defaultTimeZone];
        // 时间间隔
        not.repeatInterval = kCFCalendarUnitMinute;
        // 通知声音
        not.soundName = @"gu.mp3";
        // 标题
        not.alertTitle = @"通知来喽";
        // 内容
        not.alertBody = @"亲,上线有好礼哟,快来上线吧";
        // 提醒数字
        not.applicationIconBadgeNumber = 1;
        // 携带额外信息
        NSDictionary *info = @{@"jyh":@"key"};
        not.userInfo = info;
        // 调度通知
        [app scheduleLocalNotification:not];
        

    }
    else
    {
        NSArray *localArray = [app scheduledLocalNotifications];
        if (localArray)
        {
            for (UILocalNotification *noti in localArray)
            {
                NSDictionary *dict = noti.userInfo;
                if (dict)
                {
                    // 如果找到要取消的通知
                    NSString *inkey = [dict objectForKey:@"jyh"];
                    if ([inkey isEqualToString:@"key"])
                    {
                        [app cancelLocalNotification:noti];
                    }
                }
            }
        }
    }
}

// 第一个判断是判断switch 在打开时和关闭时
// 在switch打开时的第二个判断是因为版本的问题是否能回应registerUserNotificationSettings方法

3 紧接着 我们可以在AppDelegate.m中写如下代码

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    application.applicationIconBadgeNumber = 0;

    [[[UIAlertView alloc] initWithTitle:@"收到通知"
                                message:notification.alertBody
                               delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}

这就是在oc中实现本地通知的一个简单的方法

你可能感兴趣的:(oc本地推送)