swift实现简单的本地推送

消息推送就是在你的app周期性的给你发信息提示。今天我们看看消息推送的简单用法把!
在app delegate中实现的代码


import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

//点击应用,进入应用
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //1.检查版本
        let version = Float(UIDevice.currentDevice().systemVersion)
        if version >= 8.0 {
            //推送类型type
            let type:UIUserNotificationType = [UIUserNotificationType.Badge ,UIUserNotificationType.Sound,UIUserNotificationType.Alert]
            
            let settings = UIUserNotificationSettings(forTypes: type , categories: nil)
            
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)
 
        }
        
        
        return true
    }
//接收到本地通知
    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        print("\(notification.userInfo)")
        
           
        //将接收到的通知用webview显示出来
        let webview = UIWebView.init(frame: UIScreen.mainScreen().bounds)
        
        webview.loadRequest(NSURLRequest(URL: NSURL(string: notification.userInfo?["url"] as! String)!))
        
        self.window?.addSubview(webview)
        
        
        let allNotis:Array? = UIApplication.sharedApplication().scheduledLocalNotifications
        //遍历所有的通知
        for  localNoti:UILocalNotification in allNotis! {
            let dic:Dictionary? = localNoti.userInfo
            
            let value = dic?["url"]
            //判断url存在
            if ((value?.isEqualToString("http://www.baidu.com")) != nil){
                UIApplication.sharedApplication().cancelLocalNotification(localNoti)
            }
            
        }
        
    }

viewcontroller里面的基本设置


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //模拟 打卡功能
        
        //1.创建 本地通知对象
        let noti:UILocalNotification = UILocalNotification()
        
        //2.设置通知属性
        //设置定时推送
        let date = NSDate(timeIntervalSinceNow: 5)
        
        //推送时间
        noti.fireDate = date
        
        //设置时区
        noti.timeZone = NSTimeZone.defaultTimeZone()
        
        //设置通知的周期
        noti.repeatInterval = NSCalendarUnit.Minute
        
        //设置推送的内容
        noti.alertBody = "iOS10出来了"
        
        //设置推送的提示音
        noti.soundName = UILocalNotificationDefaultSoundName
        
        //设置应用的提示数字
        noti.applicationIconBadgeNumber = 1
        
        //设置通知传递的参数
        noti.userInfo = ["url" : "http://www.baidu.com"]
        
        //发送通知
        let application = UIApplication.sharedApplication()
        
        application.scheduleLocalNotification(noti)
        
        
    }

赶紧玩玩这个消息推送吧!!

你可能感兴趣的:(swift实现简单的本地推送)