iOS本地推送與取消本地通知—UILocalNotification的使用

1.首先我們初始化一個 UISwith

    self.swith = [[UISwitch alloc] initWithFrame:CGRectMake(80, 80, 160, 30)];
    [_swith addTarget:self action:@selector(doLocalNotifition) forControlEvents:UIControlEventValueChanged];
    [_swith setOn:NO];
    [self.view addSubview:_swith];

2.實現UISwith的方法

- (void)doLocalNotifition
{
    if (_swith.isOn==YES) {
        //初始化一個 UILocalNotification
        UILocalNotification * notification = [[UILocalNotification alloc] init];
        NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
        if (notification!=nil) {
            
            //設置 推送時間
            notification.fireDate= pushDate;
            //設置 時區
            notification.timeZone = [NSTimeZone defaultTimeZone];
            //設置 重複間隔
            notification.repeatInterval = kCFCalendarUnitDay;
            //設置 推送 時間
            notification.soundName = UILocalNotificationDefaultSoundName;
            //設置 推送提示語
            notification.alertBody = @"提示框內容5";
            //設置 icon 上 紅色數字
            notification.applicationIconBadgeNumber = 1;
            //取消 推送 用的 字典  便於識別
            NSDictionary * inforDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
            notification.userInfo =inforDic;
            //添加推送到 Application
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
        NSLog(@"開啓本地通知");
    }else if(_swith.isOn==NO){
        
        //拿到 存有 所有 推送的數組
        NSArray * array = [[UIApplication sharedApplication] scheduledLocalNotifications];
        //便利這個數組 根據 key 拿到我們想要的 UILocalNotification
        for (UILocalNotification * loc in array) {
            if ([[loc.userInfo objectForKey:@"key"] isEqualToString:@"name"]) {
                //取消 本地推送
                [[UIApplication sharedApplication] cancelLocalNotification:loc];
            }
        }

        NSLog(@"關閉本地通知");
    }
}

代碼地址:http://download.csdn.net/detail/u012405234/6432113




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章