Microsoft Azureに設置したWeb AppsからiOSへプッシュ通知を送るためにMicrosoft AzureのNotification Hubを利用してみます。(その2)
iOS:8.4.1
Xcode:6.4
Swift:1.2
Mobile Services iOS SDK:1.2.4
前回設定したMicrosoft Azureの通知ハブからメッセージを受信するための設定をiOSアプリに追加します。
1.WindowsAzureMessaging.frameworkの追加
Mobile Services iOS SDKの「iOS 1.2.4 SDK」をダウンロードします。
ダウンロードした「azuresdk-iOS-v1」の中にある「WindowsAzureMessaging.framework」をXcodeのProject navigatorの空いてる辺りにドラッグして追加します。

2.ブリッジングヘッダの追加
Mobile Service iOS SDKはObjective-CなのでSwiftで使う場合にはブリッジングヘッダが必要になるため「New File…」でファイル名を「AzureMessaging-Bridging-Header.h」とします。



作成したブリッジングヘッダを利用出来るよう「Swift Compiler」の「Objective-C Bridging Header」にパスを記述します。

作成したブリッジングヘッダの内容を以下に書き換えます。
#import "WindowsAzureMessaging/WindowsAzureMessaging.h"
3.デバイストークンの取得とAzure Notification Hubsへの登録
Azure Notification Hubs上でもデバイスを管理するため、デバイストークンを登録する処理が必要になります。なお、通知ハブへ登録されたデバイスの有効期間は90日のようです。(参考「登録管理」)
「AppDelegate.swift」の記述を以下のようにします。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Notificationを使う設定
if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0 {
// iOS Version 8.0 以上の処理
let types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
let settings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// iOS Version 8.0 より下の処理
application.registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert)
}
return true
}
// 追加
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// 通知ハブ名
let notificationHubName = "notification-ns";
// DefaultFullSharedAccessSignature
let notificationHubConnection = "Endpoint=~~~~~;SharedAccessKey=XXxxxXXXX9xxXXx9xX99";
// 通知ハブへデバイスの登録
var hub = SBNotificationHub(connectionString: notificationHubConnection, notificationHubPath: notificationHubName)
hub.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: {(error) -> Void in
if (error != nil) {
println("Regist Error:\(error)")
} else {
println("Regist Success:\(deviceToken)")
}
})
}
// 追加
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
// 通知を受信した場合の処理
println("receive notification:\(userInfo.description)")
}
次回はWeb Appsでの送信です。