Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 9, 2019 09:13
Show Gist options
  • Save KentarouKanno/e1098417db8dc57964c9 to your computer and use it in GitHub Desktop.
Save KentarouKanno/e1098417db8dc57964c9 to your computer and use it in GitHub Desktop.
RemoteNotification

RemoteNotification

★ 通知の初期化(ユーザーへの許可を促す)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
    let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories:nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()
    
    // アプリ起動時のプッシュ通知受信
    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
        if let body = remoteNotification.alertBody {
            // alertBody
        }

        if let notify = remoteNotification.userInfo {
            // UserInfo (Dictionary Data)
        }
    }
    
    return true
}

★ デバイストークン取得時に呼ばれるDelegate

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    print(deviceToken.description)
    //=> <988f1fdf 44ba05ad 3e720a72 0950d88a 4d16e67d 50721241 1c3d2bc8 545c69da>
}

★ デバイストークンの取得に失敗した時に呼ばれるDelegate

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print(error.code)
}

★ プッシュ通知のタップでアプリを起動した時に呼ばれるDelegate

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    
    print(userInfo)
    
    switch application.applicationState {
    case .Inactive:
        // アプリがバックグラウンドにいる状態で、Push通知から起動したとき
        break
    case .Active:
        // アプリ起動中にPush通知を受信
        break
    default:
        break
    }
}

★ ローカル通知の設定状況を取得する

if #available(iOS 8.0, *) {
    // iOS8.0->
    
    let status = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
    if let status = status where status == UIUserNotificationType.None {
        print("Notification None")
    } else {
        
        if let status = status {
            if status.contains(UIUserNotificationType.Badge) {
                print("Badge ON")
            }
            if status.contains(UIUserNotificationType.Sound) {
                print("Sound ON")
            }
            if status.contains(UIUserNotificationType.Alert) {
                print("Alert ON")
            }
        }
    }
} else {
    
    let status = UIApplication.sharedApplication().enabledRemoteNotificationTypes()
    if status == UIRemoteNotificationType.None {
        print("Notification None")
    } else {
        
        if status.contains(UIRemoteNotificationType.Badge) {
            print("Badge ON")
        }
        if status.contains(UIRemoteNotificationType.Sound) {
            print("Sound ON")
        }
        if status.contains(UIRemoteNotificationType.Alert) {
            print("Alert ON")
        }
    }
}

APNS Codable

let apnsData = """
{
  "aps": {
    "alert": {
      "title": "New Message",
      "body": "新しいメッセージが届きました"
    },
    "sound": "default"
  },
  "screen": "mesasge-detail",
  "messageId": 1100
}
""".data(using: .utf8)!


struct NotificationPayload: Decodable {
    var aps: Aps?
    var screen: String?
    var messageId: Int?
    
    struct Aps: Decodable {
        var alert: Alert?
        var sound: String?
    }
    
    struct Alert: Decodable {
        var title: String?
        var body: String?
    }
}

let payload = try? JSONDecoder().decode(NotificationPayload.self, from: apnsData)

payload?.aps?.alert?.title /* New Message */
payload?.aps?.alert?.body /* "新しいメッセージが届きました"  */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment