Aracılığıyla paylaş


ASP.NET kullanarak geçerli kullanıcıyı anında iletme bildirimlerine kaydetme

Genel Bakış

Bu konu başlığında, kayıt ASP.NET Web API'ASP.NET tarafından gerçekleştirildiğinde Azure Notification Hubs ile anında iletme bildirimi kaydının nasıl istendiği gösterilir. Bu konu başlığı, Notification Hubs ile kullanıcılara bildirme öğreticisini genişletir. Kimliği doğrulanmış mobil hizmeti oluşturmak için bu öğreticideki gerekli adımları zaten tamamlamış olmanız gerekir. Kullanıcıları bilgilendirme senaryosu hakkında daha fazla bilgi için bkz. Notification Hubs ile kullanıcılara bildirme.

Uygulamanızı güncelleştirme

  1. MainStoryboard_iPhone.storyboard'unuza nesne kitaplığından aşağıdaki bileşenleri ekleyin:

    • Etiket: "Notification Hubs ile Kullanıcıya Gönder"

    • Etiket: "InstallationId"

    • Etiket: "Kullanıcı"

    • Metin Alanı: "Kullanıcı"

    • Etiket: "Parola"

    • Metin Alanı: "Parola"

    • Düğme: "Oturum Aç"

      Bu noktada görsel taslak aşağıdaki gibi görünür:

      Bileşenlerin eklendiği MainStoryboard_iPhone.storyboard uygulamasının ekran görüntüsü.

  2. Yardımcı düzenleyicide, tüm anahtarlanan denetimler için çıkışlar oluşturun ve bunları çağırın, metin alanlarını Görünüm Denetleyicisi'ne (temsilci) bağlayın ve oturum açma düğmesi için bir Eylem oluşturun.

    MainStoryboard_iPhone.storyboard uygulamasında yardımcı düzenleyicinin ekran görüntüsü

    BreakingNewsViewController.h dosyanız artık aşağıdaki kodu içermelidir:

    @property (weak, nonatomic) IBOutlet UILabel *installationId;
    @property (weak, nonatomic) IBOutlet UITextField *User;
    @property (weak, nonatomic) IBOutlet UITextField *Password;
    
    - (IBAction)login:(id)sender;
    
  3. adlı DeviceInfobir sınıf oluşturun ve aşağıdaki kodu DeviceInfo.h dosyasının arabirim bölümüne kopyalayın:

    @property (readonly, nonatomic) NSString* installationId;
    @property (nonatomic) NSData* deviceToken;
    
  4. DeviceInfo.m dosyasının uygulama bölümünde aşağıdaki kodu kopyalayın:

    @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;
    }
    
  5. PushToUserAppDelegate.h içinde aşağıdaki özellik singleton'ını ekleyin:

    @property (strong, nonatomic) DeviceInfo* deviceInfo;
    
  6. didFinishLaunchingWithOptions PushToUserAppDelegate.m dosyasındaki yöntemine aşağıdaki kodu ekleyin:

    self.deviceInfo = [[DeviceInfo alloc] init];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    

    İlk satır singleton'ı DeviceInfo başlatır. İkinci satır, Notification Hubs ile Çalışmaya Başlama öğreticisini tamamladıysanız zaten mevcut olan anında iletme bildirimlerinin kaydını başlatır.

  7. PushToUserAppDelegate.m içinde AppDelegate'inizde yöntemini didRegisterForRemoteNotificationsWithDeviceToken uygulayın ve aşağıdaki kodu ekleyin:

    self.deviceInfo.deviceToken = deviceToken;
    

    Bu, istek için cihaz belirtecini ayarlar.

    Not

    Bu noktada, bu yöntemde başka bir kod olmamalıdır. Azure Notification Hubs kullanarak iOS uygulamalarınaregisterNativeWithDeviceToken anında iletme bildirimleri gönderme öğreticisini tamamladığınızda eklenen yöntemine zaten bir çağrınız varsa, bu çağrıyı açıklama satırı yapmalı veya kaldırmalısınız.

  8. PushToUserAppDelegate.m dosyasına aşağıdaki işleyici yöntemini ekleyin:

    * (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];
    }
    

    Bu yöntem, uygulamanız çalışırken bildirim aldığında kullanıcı arabiriminde bir uyarı görüntüler.

  9. PushToUserViewController.m Dosyasını açın ve aşağıdaki uygulamada klavyeyi döndürin:

    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == self.User || theTextField == self.Password) {
            [theTextField resignFirstResponder];
        }
        return YES;
    }
    
  10. dosyasındaki viewDidLoad yönteminde PushToUserViewController.m etiketi şu şekilde başlatın installationId :

    DeviceInfo* deviceInfo = [(PushToUserAppDelegate*)[[UIApplication sharedApplication]delegate] deviceInfo];
    Self.installationId.text = deviceInfo.installationId;
    
  11. arabirimine PushToUserViewController.maşağıdaki özellikleri ekleyin:

    @property (readonly) NSOperationQueue* downloadQueue;
    - (NSString*)base64forData:(NSData*)theData;
    
  12. Ardından aşağıdaki uygulamayı ekleyin:

    - (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];
    }
    
  13. XCode tarafından oluşturulan işleyici yöntemine login aşağıdaki kodu kopyalayın:

    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);
        }
    }];
    

    Bu yöntem, anında iletme bildirimleri için bir yükleme kimliği ve kanal alır ve bunu cihaz türüyle birlikte Notification Hubs'da kayıt oluşturan kimliği doğrulanmış Web API'si yöntemine gönderir. Bu Web API'sini Notification Hubs ile kullanıcılara bildirme bölümünde tanımlanmıştır.

İstemci uygulaması güncelleştirildiğinden, Notification Hubs ile kullanıcılara bildir'e dönün ve Notification Hubs'ı kullanarak bildirim göndermek için mobil hizmeti güncelleştirin.