Poznámka
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
Přehled
V tomto tématu se dozvíte, jak požádat o registraci nabízených oznámení ve službě Azure Notification Hubs při registraci pomocí webového rozhraní API ASP.NET. Toto téma rozšiřuje kurz Oznámení uživatelům pomocí Notification Hubs. Abyste mohli vytvořit ověřenou mobilní službu, musíte už dokončit požadované kroky v tomto kurzu. Další informace o scénáři upozorňování uživatelů najdete v tématu Oznámit uživatelům pomocí notification Hubs.
Aktualizace aplikace
Do MainStoryboard_iPhone.storyboard přidejte následující komponenty z knihovny objektů:
popisek: "Zaslat uživateli pomocí Notification Hubs"
štítek: "InstallationId"
štítek: "Uživatel"
textové pole: "Uživatel"
popisku: "Heslo"
textové pole: "Heslo"
tlačítko: "Přihlášení"
V tomto okamžiku váš scénář vypadá takto:
V editoru asistentů vytvořte výstupy pro všechny přepínací ovládací prvky a propojte je, propojte textová pole s View Controllerem (delegátem) a přidejte akci pro tlačítko pro přihlášení.
Váš soubor BreakingNewsViewController.h by teď měl obsahovat následující kód:
@property (weak, nonatomic) IBOutlet UILabel *installationId; @property (weak, nonatomic) IBOutlet UITextField *User; @property (weak, nonatomic) IBOutlet UITextField *Password; - (IBAction)login:(id)sender;
Vytvořte třídu s názvem
DeviceInfo
a zkopírujte následující kód do části rozhraní souboru DeviceInfo.h:@property (readonly, nonatomic) NSString* installationId; @property (nonatomic) NSData* deviceToken;
Zkopírujte následující kód v části implementace souboru 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; }
Do PushToUserAppDelegate.h přidejte následující vlastnost singleton:
@property (strong, nonatomic) DeviceInfo* deviceInfo;
Do metody
didFinishLaunchingWithOptions
v PushToUserAppDelegate.m přidejte následující kód:self.deviceInfo = [[DeviceInfo alloc] init]; [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
První řádek inicializuje
DeviceInfo
singleton. Druhý řádek spustí registraci pro push notifikace, která už existuje, pokud jste již dokončili kurz Začínáme s Notification Hubs.V PushToUserAppDelegate.m implementujte metodu
didRegisterForRemoteNotificationsWithDeviceToken
v AppDelegate a přidejte následující kód:self.deviceInfo.deviceToken = deviceToken;
Tím se nastaví token zařízení pro požadavek.
Poznámka:
V tomto okamžiku by neměl být v této metodě žádný jiný kód. Pokud už máte volání metody
registerNativeWithDeviceToken
, která byla přidána, když jste dokončili tutoriál Odesílání push oznámení do aplikací pro iOS pomocí služby Azure Notification Hubs, musíte toto volání okomentovat nebo odebrat.Do souboru
PushToUserAppDelegate.m
přidejte následující metodu obslužné rutiny:* (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]; }
Tato metoda zobrazí upozornění v uživatelském rozhraní, když vaše aplikace obdrží oznámení, když je spuštěná.
Otevřete soubor
PushToUserViewController.m
a vraťte klávesnici v následující implementaci:- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { if (theTextField == self.User || theTextField == self.Password) { [theTextField resignFirstResponder]; } return YES; }
V
viewDidLoad
metodě v souboruPushToUserViewController.m
inicializovat popisekinstallationId
následujícím způsobem:DeviceInfo* deviceInfo = [(PushToUserAppDelegate*)[[UIApplication sharedApplication]delegate] deviceInfo]; Self.installationId.text = deviceInfo.installationId;
V rozhraní
PushToUserViewController.m
přidejte následující vlastnosti:@property (readonly) NSOperationQueue* downloadQueue; - (NSString*)base64forData:(NSData*)theData;
Pak přidejte následující implementaci:
- (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]; }
Do metody obslužné rutiny
login
vytvořené pomocí XCode zkopírujte následující kód: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); } }];
Tato metoda získá ID instalace i kanál pro nabízená oznámení a odešle ho spolu s typem zařízení do ověřené metody webového rozhraní API, která vytvoří registraci v Notification Hubs. Toto webové rozhraní API bylo definováno v Oznámit uživatelům pomocí notification Hubs.
Teď, když je klientská aplikace aktualizovaná, vraťte se do Informovat uživatele pomocí Notification Hubs a aktualizujte mobilní službu tak, aby odesílala oznámení pomocí Notification Hubs.