L
Published on
· Last modified on
· Public

通用 - 本地通知

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch.

    //创建本地推送 [self createLocalNotify];

    self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }

pragma mark - 创建本地推送

-(void)createLocalNotify { NSLog(@"创建本地推送通知");

// 创建一个本地推送对象
UILocalNotification *notification = [[UILocalNotification alloc] init];

//设置时间为10秒之后
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];

//设置推送时间
notification.fireDate = pushDate;

//设置时区
notification.timeZone = [NSTimeZone defaultTimeZone];

//设置重复间隔
notification.repeatInterval = kCFCalendarUnitDay;

//推送声音
notification.soundName = UILocalNotificationDefaultSoundName;

//推送内容
notification.alertBody = @"这是本地推送内容";

//设置Badge 显示在icon上的红色圈中的数子
notification.applicationIconBadgeNumber = 1;

//设置userinfo 方便在之后需要撤销的时候使用
NSDictionary *info = [NSDictionary dictionaryWithObject:@"hello"forKey:@"key"];
notification.userInfo = info;

//添加推送到UIApplication
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:notification];

NSLog(@"10s后能接收到通知");

}

pragma mark - 接收本地推送消息

  • (void)application:(UIApplication )application didReceiveLocalNotification:(UILocalNotification)notification{

    NSLog(@"接收本地推送消息");

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地推送" message:notification.alertBody delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show];

    // 图标上的数字减1 application.applicationIconBadgeNumber = 0;

    //接收到数据之后 解除本地通知 [self closeNotify];

}

pragma mark - 解除本地通知

-(void)closeNotify { NSLog(@"开始解除本地推送");

//获得UIApplication
UIApplication *app = [UIApplication sharedApplication];

//获取本地推送数组
NSArray *localArray = [app scheduledLocalNotifications];

//遍历数组,找到之前创建的本地通知
for (UILocalNotification *localNotification in localArray) {

    NSDictionary *dict = localNotification.userInfo;
    NSString *key = [dict objectForKey:@"key"];
    if ([key isEqualToString:@"hello"]) {

        //解除推送
        [app cancelLocalNotification:localNotification];

        NSLog(@"成功解除");

        break;
    }
}

}

N
Published on

大神猴赛雷!

I
Published on

求星

P
Published on

求星 已星

Sign in or Sign up Leave Comment