2011-09-20 14 views
10

Ho letto un sacco di tutorial per questo e volevo solo sapere se ti questo è il modo giusto per fare questoinvio dispositivo token per server di

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken 
{ 
    NSLog(@"My token is: %@", deviceToken); 

    NSString* newToken = [deviceToken description]; 

    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; 
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""]; 


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com./filecreate.php?token=%@",newToken]; 

    NSURL *url = [[NSURL alloc] initWithString:urlString]; 

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 

    NSData *urlData; 
    NSURLResponse *response; 
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]; 

} 

eventuali consigli sono più che benvenuti.

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken 
{ 

    const char* data = [deviceToken bytes]; 
    NSMutableString* token = [NSMutableString string]; 

    for (int i = 0; i < [deviceToken length]; i++) { 
     [token appendFormat:@"%02.2hhX", data[i]]; 
    } 


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",token]; 

    NSURL *url = [[NSURL alloc] initWithString:urlString]; 

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 
    NSData *urlData; 
    NSURLResponse *response; 
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]; 

} 

La mia applicazione funziona con entrambi i codici, ma qual è la strada giusta?

+0

Il codice non funziona? – Nekto

+1

sembra buono, ma, vorrei 1, aggiungere meccanismo di recupero degli errori (se la richiesta fallisce, perderai il tuo token!) Eb, usa una richiesta asincrona. – mja

+1

asincrono? come intendi. Per favore dammi alcune linee guida per il meccanismo di recupero degli errori anche. Il codice funziona, ma mi chiedevo se questo è il modo giusto, perché ho letto da qualche parte che 'NSString * newToken = [deviceToken description];' questo non è il modo giusto per ottenere dati nella stringa – Spire

risposta

18

Come MJA detto nei commenti, è meglio aggiungere meccanismo di recupero di errore (se la richiesta non riesce si perde il token) e utilizzare richiesta asincrona (inviare gettone in background)

Nella tua AppDelegate.m:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken 
{ 
    NSString * token = [NSString stringWithFormat:@"%@", deviceToken]; 
    //Format token as you need: 
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""]; 
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""]; 
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""]; 

    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"apnsToken"]; //save token to resend it if request fails 
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"apnsTokenSentSuccessfully"]; // set flag for request status 
    [DataUpdater sendUserToken]; //send token 
} 

Per inviare gettone creare nuova classe (o utilizzare uno dei esistente):
DataUpdater.h

#import <Foundation/Foundation.h> 

@interface DataUpdater : NSObject  
+ (void)sendUserToken; 
@end 

DataUpdater.m

#import "DataUpdater.h" 

@implementation DataUpdater 

+ (void)sendUserToken { 
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"apnsTokenSentSuccessfully"]) { 
     NSLog(@"apnsTokenSentSuccessfully already"); 
     return; 
    } 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"apnsToken"]]]; //set here your URL 

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    { 
     if (error == nil) { 
      [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"apnsTokenSentSuccessfully"]; 
      NSLog(@"Token is being sent successfully"); 
      //you can check server response here if you need 
     } 
    }]; 
} 

@end 

Poi si può chiamare [DataUpdater sendUserToken]; nel vostro controller quando appare connessione ad internet, o periodicamente, o in - (void) viewDidLoad o - (void) viewWillAppear metodi

mio consiglia:
1) Io uso AFNetworking di inviare richiesta asincrona e controllo server di JSON risposta
2) Alcune volte è meglio usare servizi come Parse di lavorare con le notifiche push

+0

Thx amico ma questa è una domanda molto molto vecchia. Accetto la risposta, potrebbe giovare a qualcuno. – Spire

+3

Penso che dovresti chiamare [synchronize] (https://developer.apple.com/library/mac/documentation/cacao/reference/foundation/classes/nsuserdefaults_class/reference/reference.html # // apple_ref/occ/instm/NSUserDefaults/synchronize) dopo aver memorizzato le informazioni. – nsacerdote

0

Nel metodo didFinishLaunchingWithOptions

[[UIApplication sharedApplication] registerForRemoteNotificationTypes: 
    (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; 

Dopo aver fatto sopra le righe di codice, aggiungere il seguente metodo

#pragma mark - 
#pragma mark Push Notifications 
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{ 
NSString *token_string = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""] 
          stringByReplacingOccurrencesOfString:@">" withString:@""] 
          stringByReplacingOccurrencesOfString: @" " withString: @""]; 
NSString* strURL = [NSString stringWithFormat:@"http://www.sample.com?device_token=%@&type=IOS",token_string]; 
strURL=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSLog(@"%@",strURL); 
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; 
NSLog(@"content---%@", fileData); 
} 
+0

Il codice in didFinishLaunchingWithoptions deve essere aggiunto per ottenere le notifiche push –