概要
このトピックでは、ASP.NET Web API によって登録が実行されたときに、Azure Notification Hubs にプッシュ通知の登録を要求する方法について説明します。 このトピックでは、 Notification Hubs を使用してユーザーに通知するチュートリアルを拡張します。 認証されたモバイル サービスを作成するには、そのチュートリアルで必要な手順を既に完了している必要があります。 ユーザーへの通知シナリオの詳細については、「 Notification Hubs を使用してユーザーに通知する」を参照してください。
アプリを更新する
MainStoryboard_iPhone.storyboard で、オブジェクト ライブラリから次のコンポーネントを追加します。
ラベル: "Notification Hubs を使用してユーザーにプッシュする"
ラベル: "InstallationId"
ラベル: "User"
テキスト フィールド: "User"
ラベル: "Password"
テキスト フィールド: "Password"
ボタン: "ログイン"
この時点で、ストーリーボードは次のようになります。
アシスタント エディターで、切り替えたすべてのコントロールのアウトレットを作成して呼び出し、テキスト フィールドをビュー コントローラー (デリゲート) に接続し、ログイン ボタンのアクションを作成します。
BreakingNewsViewController.h ファイルに次のコードが含まれているはずです。
@property (weak, nonatomic) IBOutlet UILabel *installationId; @property (weak, nonatomic) IBOutlet UITextField *User; @property (weak, nonatomic) IBOutlet UITextField *Password; - (IBAction)login:(id)sender;
DeviceInfo
という名前のクラスを作成し、次のコードを DeviceInfo.h ファイルのインターフェイス セクションにコピーします。@property (readonly, nonatomic) NSString* installationId; @property (nonatomic) NSData* deviceToken;
DeviceInfo.m ファイルの実装セクションで次のコードをコピーします。
@synthesize installationId = _installationId; - (id)init { if (!(self = [super init])) return nil; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; _installationId = [defaults stringForKey:@"PushToUserInstallationId"]; if(!_installationId) { CFUUIDRef newUUID = CFUUIDCreate(kCFAllocatorDefault); _installationId = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, newUUID); CFRelease(newUUID); //store the install ID so we don't generate a new one next time [defaults setObject:_installationId forKey:@"PushToUserInstallationId"]; [defaults synchronize]; } return self; } - (NSString*)getDeviceTokenInHex { const unsigned *tokenBytes = [[self deviceToken] bytes]; NSString *hexToken = [NSString stringWithFormat:@"%08X%08X%08X%08X%08X%08X%08X%08X", ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]), ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]), ntohl(tokenBytes[6]), ntohl(tokenBytes[7])]; return hexToken; }
PushToUserAppDelegate.h で、次のプロパティ シングルトンを追加します。
@property (strong, nonatomic) DeviceInfo* deviceInfo;
PushToUserAppDelegate.m の
didFinishLaunchingWithOptions
メソッドに、次のコードを追加します。self.deviceInfo = [[DeviceInfo alloc] init]; [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
最初の行は、
DeviceInfo
シングルトンを初期化します。 2 行目はプッシュ通知の登録を開始します。これは、 Notification Hubs の概要 チュートリアルを既に完了している場合に既に存在します。PushToUserAppDelegate.m で、AppDelegate に
didRegisterForRemoteNotificationsWithDeviceToken
メソッドを実装し、次のコードを追加します。self.deviceInfo.deviceToken = deviceToken;
これにより、要求のデバイス トークンが設定されます。
注
この時点で、このメソッドには他のコードは含まれません。 Azure Notification Hubs を使用して iOS アプリにプッシュ通知を送信するチュートリアルを完了したときに追加された
registerNativeWithDeviceToken
メソッドの呼び出しが既にある場合は、その呼び出しをコメント アウトするか削除する必要があります。PushToUserAppDelegate.m
ファイルに、次のハンドラー メソッドを追加します。* (void) application:(UIApplication *) application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSLog(@"%@", userInfo); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification" message: [userInfo objectForKey:@"inAppMessage"] delegate:nil cancelButtonTitle: @"OK" otherButtonTitles:nil, nil]; [alert show]; }
このメソッドは、実行中にアプリが通知を受信したときに、UI にアラートを表示します。
PushToUserViewController.m
ファイルを開き、次の実装でキーボードを返します。- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { if (theTextField == self.User || theTextField == self.Password) { [theTextField resignFirstResponder]; } return YES; }
PushToUserViewController.m
ファイルのviewDidLoad
メソッドで、次のようにinstallationId
ラベルを初期化します。DeviceInfo* deviceInfo = [(PushToUserAppDelegate*)[[UIApplication sharedApplication]delegate] deviceInfo]; Self.installationId.text = deviceInfo.installationId;
PushToUserViewController.m
のインターフェイスに次のプロパティを追加します。@property (readonly) NSOperationQueue* downloadQueue; - (NSString*)base64forData:(NSData*)theData;
次に、次の実装を追加します。
- (NSOperationQueue *)downloadQueue { if (!_downloadQueue) { _downloadQueue = [[NSOperationQueue alloc] init]; _downloadQueue.name = @"Download Queue"; _downloadQueue.maxConcurrentOperationCount = 1; } return _downloadQueue; } // base64 encoding - (NSString*)base64forData:(NSData*)theData { const uint8_t* input = (const uint8_t*)[theData bytes]; NSInteger length = [theData length]; static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t* output = (uint8_t*)data.mutableBytes; NSInteger i; for (i=0; i < length; i += 3) { NSInteger value = 0; NSInteger j; for (j = i; j < (i + 3); j++) { value <<= 8; if (j < length) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / 3) * 4; output[theIndex + 0] = table[(value >> 18) & 0x3F]; output[theIndex + 1] = table[(value >> 12) & 0x3F]; output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; } return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; }
XCode によって作成された
login
ハンドラー メソッドに次のコードをコピーします。DeviceInfo* deviceInfo = [(PushToUserAppDelegate*)[[UIApplication sharedApplication]delegate] deviceInfo]; // build JSON NSString* json = [NSString stringWithFormat:@"{\"platform\":\"ios\", \"instId\":\"%@\", \"deviceToken\":\"%@\"}", deviceInfo.installationId, [deviceInfo getDeviceTokenInHex]]; // build auth string NSString* authString = [NSString stringWithFormat:@"%@:%@", self.User.text, self.Password.text]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://nhnotifyuser.azurewebsites.net/api/register"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]]; [request addValue:[@([json lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) description] forHTTPHeaderField:@"Content-Length"]; [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request addValue:[NSString stringWithFormat:@"Basic %@",[self base64forData:[authString dataUsingEncoding:NSUTF8StringEncoding]]] forHTTPHeaderField:@"Authorization"]; // connect with POST [NSURLConnection sendAsynchronousRequest:request queue:[self downloadQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) { // add UIAlert depending on response. if (error != nil) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; if ([httpResponse statusCode] == 200) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Back-end registration" message:@"Registration successful" delegate:nil cancelButtonTitle: @"OK" otherButtonTitles:nil, nil]; [alert show]; } else { NSLog(@"status: %ld", (long)[httpResponse statusCode]); } } else { NSLog(@"error: %@", error); } }];
このメソッドは、プッシュ通知のインストール ID とチャネルの両方を取得し、デバイスの種類と共に、Notification Hubs に登録を作成する認証済みの Web API メソッドに送信します。 この Web API は、「 Notification Hubs を使用してユーザーに通知する」で定義されています。
クライアント アプリが更新されたので、Notification Hubs を使用してユーザーに通知 に戻り、Notification Hubs を使用して通知を送信するようにモバイル サービスを更新します。