最新消息:20210917 已从crifan.com换到crifan.org

[已解决]swift的本地通知在模拟器生效但iPhone真机不生效

iphone crifan 1982浏览 0评论

swift的代码:

    func sendNotification(newMessage:Message){
        var notifTitle = ""
        var notifBody = ""
        (notifTitle, notifBody) = genMesageTitleBody(newMessage)
        print("notifTitle=\(notifTitle), notifBody=\(notifBody)")
        let localNotif = UILocalNotification()
        localNotif.fireDate = NSDate(timeIntervalSinceNow: 0.5)
        localNotif.timeZone = NSTimeZone.defaultTimeZone()
        if #available(iOS 8.2, *) {
            localNotif.alertTitle = notifTitle
        } else {
            // Fallback on earlier versions
        }
        localNotif.alertBody = notifBody
        localNotif.soundName = UILocalNotificationDefaultSoundName
        localNotif.alertLaunchImage = ""
        localNotif.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
        UIApplication.sharedApplication().scheduleLocalNotification(localNotif)
    }

实现本地通知

然后模拟器中至少有通知,生效了:

但是刷了iOS 9.2.1的iPhone6,却没有生效:

没有本地通知。。。

其中,iPhone中的app本身已经设置允许通知了:

但是却很怪:

好像对于

applicationIconBadgeNumber

有时候生效了:

点击app后,就刷新了桌面图片的badge

但是如果app处于background,就没有提示

但是始终都没有:

本地通知显示

也没有声音

就只有applicationIconBadgeNumber好像是有时候生效了。。。

搜:

swift local notification not work

swift local notification not work ios 9.2

Daily Local Notification In Swift iOS 9.2 – Stack Overflow

xcode – iOS Swift Local notification not "popping up" – Stack Overflow

swift2 – Actions buttons not showing up in local notifications ios 9.2 swift 2 – Stack Overflow

How to set local alerts using UILocalNotification – Swift 2 example code

好像是缺少了:

UIUserNotificationSettings

的设置了。。。

之前只是注册了badge:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
。。。
        //enable notification
        let notifSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge],
            categories: nil)
        application.registerUserNotificationSettings(notifSettings)
        //reset badge number
        application.applicationIconBadgeNumber = 0
        return true
    }

所以去改为:

        let notifSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound],
            categories: nil)
        application.registerUserNotificationSettings(notifSettings)

再去试试效果:

然后终于基本搞清楚了:

其实之前本地通知,就已经生效了

但是是显示在:通知中心 的,即:

顶部下拉后,看到的“通知”中:

然后进入设置中,修改通知显示位置:

不要选:在“通知中心”中显示

然后收到新消息后,即可收到顶部弹出的通知了:

但是还是有个问题:

和iOS模拟器相比,iPhone6真机中通知显示的比较滞后:

感觉要等个几秒才能显示

或者根本就漏掉了,不显示

而iOS模拟器中,每条消息,都可以及时显示通知,比较稳定

iPhone6通知显示的不稳定

转载请注明:在路上 » [已解决]swift的本地通知在模拟器生效但iPhone真机不生效

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
93 queries in 0.178 seconds, using 23.36MB memory