ios(推送)之本地推送 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

ios(推送)之本地推送

发表时间:2021-1-4

发布人:葵宇科技

浏览次数:29


iOS上有两种消息通知,一种是本地消息(Local Notification),一种是远程消息(Push Notification,也叫Remote Notification),设计这两种通知的目的都是为了提醒用户,现在有些什么新鲜的事情发生了,吸引用户重新打开应用。本地推送也可以通过服务器控制,比如说如果有新消息了,推送消息,但是,前提是程序必须是打开的,而远程推送,是通过苹果APNS服务器,推送给手机,手机在推送给具体的哪个程序,一般远程推送用到的比较多,先介绍下本地推送,下节在介绍远程推送。
本地推送:
首先,先在appdelegate中注册:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];//注册本地推送
    
    // Override point for customization after application launch.
    return YES;
}

然后,在具体的viewcontroller中实现推送:
- (IBAction)localPushNow:(id)sender {
 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //本地推送
        UILocalNotification*notification = [[UILocalNotification alloc]init];
        NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
        if (notification != nil) {
            notification.fireDate = pushDate;
            notification.timeZone = [NSTimeZone defaultTimeZone];
            notification.repeatInterval = kCFCalendarUnitDay;
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.alertBody = @"hello,world";
            notification.applicationIconBadgeNumber = 0;
            NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"];
            notification.userInfo = info;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            
        }
    });

}

在appdelegate中会接收到推送信息:

//接收本地推送
//接收本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"%@",notification.alertBody);
    UILabel*label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, 160, 20);
    label.layer.cornerRadius = 10;
    label.backgroundColor = [UIColor blackColor];
    label.text = notification.alertBody;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12];
    label.textAlignment = NSTextAlignmentCenter;
    
    [self.window addSubview:label];
}

过程中可能会出现如下状况:
Attempting to schedule a local notification……with a sound but haven't received permission from the user to play sounds
Attempting to schedule a local notification……with an alert but haven't received permission from the user to display alerts
可能是因为你没有注册,或者设置中没有开启推送功能,

相关案例查看更多