Home > AI > Uncategorized

Swift – Apns

苹果通知分4类:

1)Apns,远程通知

2)静默通知(远程通知一种,应用更新数据,用户不知)

3)本地通知

4)NotificationCenter传值

 

这里和大家分享下Apns的代码:

>>>>Apns.swift<<<<<

import Foundation
import UserNotifications
import UIKit


class APNS {
    static func registerAPNS(_ appDelegate: AppDelegate){
        if #available(iOS 10.0, *){
            let center = UNUserNotificationCenter.current()
            center.delegate = appDelegate //open 3 methods
            center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if granted && error == nil {
                    //it has be executed in main thread, or error will occur
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                }
            }
        }
    }
    
    static func convertDeviceToken(_ deviceToken: Data){
        //get deviceToken generated by APNs
        //send the deviceToken combined with other infos, such as app version, userInfo, to provider server
        //deviceToken may change, remember to check and update by UserDefaults
        
        //convert deviceToken from 32byte to string
        let device = NSData(data: deviceToken)
        let deviceId = device.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
        print("deviceToken", deviceId)

        //update deviceToken
        let oldDeviceToken = UserDefaults.standard.string(forKey: User.AccountInfo.deviceToken)
        if oldDeviceToken == nil || deviceId != oldDeviceToken {
            UserDefaults.standard.set(deviceId, forKey: User.AccountInfo.deviceToken)
            print("refresh deviceToken")
        }
    
    }

}

>>>>>AppDelegate.swift<<<<<

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate{

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.  
        print("target", TARGET_OS_IOS, TARGET_OS_TV)
        return true
    }

  
    //3 methods
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("err")
    }
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("did Remote")
    }
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("receive")
    }
}

>>>>>Capabilities打开权限<<<<<

付费开发者账号才有。

 

 

 

 

Related posts:

Leave a Reply