设为首页 加入收藏

TOP

SWIFT推送之本地推送(UILocalNotification)(一)
2017-10-10 12:14:19 】 浏览:9118
Tags:SWIFT 推送 本地 UILocalNotification

SWIFT推送之本地推送(UILocalNotification)

本地推送通知是通过实例化UILocalNotification实现的。要实现本地化推送可以在AppDelegate.swift中添加代码实现,本事例是一个当App进入后台时推送一条消息给用户。

1.首先在didFinishLaunchingWithOptions方法内添加代码,IOS8推送消息首先要获得用户的同意,在初次安装App时会提示用户是否允许程序推送消息,此方法是App第一次运行的时候被执行一次,每次从后台激活时不执行该方法.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8 {

            //APService.registerForRemoteNotificationTypes(

                //UIUserNotificationType.Badge.rawValue |

                //UIUserNotificationType.Sound.rawValue |

                //UIUserNotificationType.Alert.rawValue,

                //categories: nil)

            

            application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes:

                UIUserNotificationType.Badge |

                UIUserNotificationType.Sound |

                UIUserNotificationType.Alert, categories: nil))

        

        }

        

        APService.setupWithOption(launchOptions)

        return true

    }

 2.有几个方法要说一下,

   1.func applicationWillResignActive(application: UIApplication){} 当App既将进入后台、锁屏、有电话进来时会触发此事件

   2.func applicationDidEnterBackground(application: UIApplication) {} 当App进入后台时触发此事件

   3.func applicationWillEnterForeground(application: UIApplication) {} 当App从后台即将回到前台时触发此事件

   4.func applicationDidBecomeActive(application: UIApplication) {}当App变成活动状态时触发此事件

   5.func applicationWillTerminate(application: UIApplication) {} 当App退出时触发此方法,一般用于保存某些特定的数据

此时在applicationDidEnterBackground方法内写入以下代码:

func applicationDidEnterBackground(application: UIApplication) {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        UIApplication.sharedApplication().cancelAllLocalNotifications()

        

        var notification = UILocalNotification()

        //notification.fireDate = NSDate().dateByAddingTimeInterval(1)

        //setting timeZone as localTimeZone

        notification.timeZone = NSTimeZone.localTimeZone()

        notification.repeatInterval = NSCalendarUnit.CalendarUnitDay

        notification.alertTitle = "This is a local notification

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇解决问题的思路(如故事版里面有.. 下一篇WKWebView进度及title

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目