Swift

谈谈ios远程推送通知,注册与反注册(swift)

2019-01-07  本文已影响0人  Jason_风筝
写在前面
现在大部分的app都有Push的功能,这里我们讨论一下反注册与注册远程通知
你要知道

注册远程通知并不难, 但怎么反注册呢,我们都知道, 远程通知的关闭,可以在手机-> setting 中关闭. 那里的关闭是手机对app权限.可以理解成总开关吧.app 中也可以反注册.如果手机中的通知权限是打开的,那怎么通过app 控制关闭远程通知呢.下面我们来说说

注册远程通知
 let appDelegate = UIApplication.shared.delegate as! AppDelegate

        if #available(iOS 10.0, *) {
            let notifCenter = UNUserNotificationCenter.current()
            notifCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (registered, error) in
                #if DEBUG
                if registered {
                    mxPrint("notification authorization granted")
                } else {
                    mxPrint("notification authorization not granted,\nerror: \(error)")
                }
                #endif
            }
            // 实现代理的方法, 接收到通知会调用.
            notifCenter.delegate = appDelegate;
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
application.registerForRemoteNotifications()
接收通知
   @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        mxPrint("Notification received: \(response.notification.request.content.userInfo)")
        if UIApplication.shared.applicationState != .background {
           
        }
    }

    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler handler: @escaping (UIBackgroundFetchResult) -> Void) {
        mxPrint("Notification received: \(userInfo)")
        if UIApplication.shared.applicationState != .background {
        }
    }

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      ///  从状态栏点击push打开app
     if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
            if UIApplication.shared.applicationState != .background {
                
            }
        }
    }
反注册通知
 if #available(iOS 10.0, *) {
                let notifCenter = UNUserNotificationCenter.current()
                notifCenter.requestAuthorization(options: []) { (registered, error) in
                    #if DEBUG
                        if registered {
                            mxPrint("notification authorization granted")
                        } else {
                            mxPrint("notification authorization not granted,\nerror: \(error)")
                        }
                    #endif
                }
                notifCenter.delegate = nil
            } else {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(settings)
            }

UIApplication.shared.unregisterForRemoteNotifications()
判断手机设置中的通知权限是否开启
// 不为0表示可以接收推送
UIApplication.shared.currentUserNotificationSettings?.types != UIUserNotificationType.init(rawValue: 0) 
进入手机设置->app中心, 开启通知权限
 if let url = URL(string: UIApplicationOpenSettingsURLString) , UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.openURL(url)
  }
   NotificationCenter.default.addObserver(self, selector: #selector(becomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
   deinit {
        NotificationCenter.default.removeObserver(self)
    }
 ///becomeActive
@objc func becomeActive() {
    if UIApplication.shared.currentUserNotificationSettings?.types != UIUserNotificationType.init(rawValue: 0)  {
            // 开启了通知权限 
    }
  }
自定义print

func mxPrint<T>(_ message:T,file:String = #file,_ func:String = #function,_ lineNumber:Int = #line){

    #if DEBUG
    let file = (file as NSString).lastPathComponent;
    print("\(file):(\(lineNumber))--print:\(message)");
    #endif
    
}

-- 如果对你有帮助的话, 请留个 "喜欢"

上一篇 下一篇

猜你喜欢

热点阅读