Swift

iOS LocalNotification 和 RemoteNotification Tips

1. 通知权限获得, App 启动时会询问, 是否允许接收通知。
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate{
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        UNUserNotificationCenter.current().delegate = self
        // 通知権限を取得
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            granted, error in
            if granted {
                DispatchQueue.main.async(execute: {
                    // 通过UIApplication注册远程通知。 
                    // appWatch没有这段代码,appWatch所以不能注册远程通知服务。
                    UIApplication.shared.registerForRemoteNotifications()
                })
            }
        }
        return true
    }
2. RemoteNotification注册成功后, 会激活AppDelegate中下面的方法。得到 从苹果Apns返回的deviceToken。
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let uuid = UIDevice.current.identifierForVendor!.uuidString
        let deviceTokenStr = deviceToken.hexString
    }

extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}
3. 在AppDelegate实装下面的两个方法,  App接收通知到以后, 会激活下面的方法。
    func userNotificationCenter(_ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([.badge, .alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
4. 发送LocalNotification例子。
            // ローカル通知
            let content = UNMutableNotificationContent()
            content.title = "本地通知"
            // 通知消息体
            content.body = "通知"
            // 通知声音, 可以自定义
            content.sound = UNNotificationSound.default
            
            // トリガー
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
            let requestIdentifier = "com.localNotification." + String(Date().timeIntervalSince1970)
            
            // 通知リクエスト
            let request = UNNotificationRequest(identifier: requestIdentifier,
                                                content: content, trigger: trigger)
            
            // 通知メッセージを送信
            UNUserNotificationCenter.current().add(request) { error in
                if error == nil {
                    print("Time Interval Notification scheduled: \(requestIdentifier)")
                }else{
                    print("Time error: \(String(describing: error))")
                }
            }
5. 通过NodeJs 发送RemoteNotification。
// 需要npm install apn
package.json
{
  "name": "RemoteNotificationSample",
  "version": "1.0.0",
  "description": "RemoteNotificationSample",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "apn": "^2.2.0"
  }
}
// 一部分nodejs代码

const apn = require("apn");

var options = {
  // 发送RemoteNotification,需要有P12证书。
  pfx: "./xxxxx.p12",
  // P12证书 密码
  passphrase: "xxxxxx",
  production: true
};

var apnProvider = new apn.Provider(options);
var note = new apn.Notification();

note.alert = "这是一个RemoteNotification";
note.payload = { 'messageFrom': 'リモート通知' };
// 和App 的Bundle Id需要一致
note.topic = "com.xxx.xxx.xxx";
note.sound = "ping.aiff";

//  通过apnProvider发送RemoteNotification
 apnProvider.send(note, deviceToken).then((result) => {
    console.log(result.failed)
  });

6.LocalNotification 和 RemoteNotification总结

[table id=1 /]