mBaas (nifty) + Swift3로 푸시 알림 사용
게재해 둡니다.
번거로움
1. 구현 절차 Cocoapods에서 NCMB 설치
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'push_sample' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'NCMB', :git => 'https://github.com/NIFTYCloud-mbaas/ncmb_ios.git'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = "3.0"
end
end
end
2. 라이브러리 추가 및 Capability 설정
![](https://s1.md5.ltd/image/a8b00993b9af849df002b021fa12f58f.png)
![](https://s1.md5.ltd/image/21269c9af4fbc111f6d34e76cd464a32.png)
![](https://s1.md5.ltd/image/412545d8458a1615b15ad4e31d6a97e3.png)
빌드하지 않으면 Apple Developer의
Select an App ID for your Apple Push Notification service SSL Certificate (Sandbox)
에서 선택할 수 없다고 생각합니다.
3. 개발자 센터에서 통지용 인증서 작성 및 통지 이용 설정
![](https://s1.md5.ltd/image/5843398344751d27ef545d92a7e0780d.png)
![](https://s1.md5.ltd/image/e2d8bcf13758c7bbf3ba4ae6a6c9531f.png)
키를 다운로드하고 다운로드한 키 파일을 더블 클릭하여 키체인에 등록
대상 앱에서 푸시 알림을 사용하기 위해 Active로 설정
![](https://s1.md5.ltd/image/63c52aee28aad7ec5a435b921c540ce9.png)
4. Nifty 클라우드의 모바일 백엔드에서 푸시 알림 이용을 위한 키 생성 준비
Mac Finder -> 응용 프로그램 -> 유틸리티 -> 키체인 액세스 시작
![](https://s1.md5.ltd/image/9cb22983eca8abfc879f3e53d0f82394.png)
![](https://s1.md5.ltd/image/f57045dd8d2134a9b77c27441715d867.png)
여기가 공백이 아니면 알림시 오류가 발생합니다.
![](https://s1.md5.ltd/image/017d7f2eaed3288e102f8643d791eb13.png)
작성한 p12 파일을 적당한 장소에 저장합니다.
5. Nifty 클라우드의 모바일 백엔드에서 푸시 알림 설정
![](https://s1.md5.ltd/image/3194ddec2c3876b10513002cdfd90b78.png)
![](https://s1.md5.ltd/image/4119b01b72adb6edbf5627efabd3d880.png)
6.AppDelegate.swift에 알림 수락 구현
AppDelegate.swift
import UIKit
import NCMB
import UserNotificationsUI
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let applicationkey = "ニフティクラウドのmbile backendで生成したキー"
let clientkey = "ニフティクラウドのmbile backendで生成したキー"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NCMB.setApplicationKey(applicationkey, clientKey: clientkey)
// デバイストークンの要求
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
return true
}
// UIApplication.shared.registerForRemoteNotifications()によって呼び出される
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
// 端末情報を扱うNCMBInstallationのインスタンスを作成
let installation = NCMBInstallation.current()
// デバイストークンの設定
installation?.setDeviceTokenFrom(deviceToken as Data!)
// 端末情報をデータストアに登録
installation?.saveInBackground { (error) -> Void in
if (error != nil){
// 端末情報の登録に失敗した時の処理
if ((error as! NSError).code == 409001){
// 失敗した原因がデバイストークンの重複だった場合
// 端末情報を上書き保存する
self.updateExistInstallation(currentInstallation: installation!)
}else{
// デバイストークンの重複以外のエラーが返ってきた場合
}
}else{
// 端末情報の登録に成功した時の処理
}
}
}
// 端末情報を上書き保存するupdateExistInstallationメソッドを用意
func updateExistInstallation(currentInstallation : NCMBInstallation){
let installationQuery: NCMBQuery = NCMBInstallation.query()
installationQuery.whereKey("deviceToken", equalTo:currentInstallation.deviceToken)
do {
let searchDevice = try installationQuery.getFirstObject()
// 端末情報の検索に成功した場合
// 上書き保存する
currentInstallation.objectId = (searchDevice as AnyObject).objectId
currentInstallation.saveInBackground { (error) -> Void in
if (error != nil){
// 端末情報の登録に失敗した時の処理
}else{
// 端末情報の登録に成功した時の処理
}
}
} catch _ as NSError {
// 端末情報の検索に失敗した場合の処理
}
}
7. 통지 수신 확인
![](https://s1.md5.ltd/image/35de8d1360120408c9e82aeb2b24339c.png)
앱을 백그라운드로 만들거나 종료하고 기다립니다.
![](https://s1.md5.ltd/image/a22376ab79f059a2d9d8127388446a55.png)
무사히 전화를 받으면 첫걸음이 완료됩니다.
이 구현으로 할 수없는 일
할 수없는 일이지만,
1. 앱 종료 시 알림 메시지를 탭해도 앱이 시작되지 않음
2. 알림에서 앱으로 전환했을 때 특정 동작을 시키는 구현이 되어 있지 않다
3. 릴리스 환경시의 과제의 검증이 되어 있지 않다.
등, 많이 있기 때문에, 우선 어떤 것인가 시험하고 싶다고 하는 분의 도움이 된다고 생각합니다.
Reference
이 문제에 관하여(mBaas (nifty) + Swift3로 푸시 알림 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/Syn256/items/1f19b8527bac420445f9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)