Зарегистрироваться для Apple Push Notification в асинхронном режиме или в фоновом режиме - PullRequest
3 голосов
/ 22 февраля 2012

в своем приложении я использую push-уведомления, и мне кажется, что запрос на регистрацию для push занимает некоторое время, что останавливает мое приложение от немедленного отображения контента и отображения только черного экрана, пока токен устройства не вернется.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    ....

    NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] 
     registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge | 
      UIRemoteNotificationTypeSound)];

    ....

    return self;
}

Как я могу сделать это asynchrounus или в фоновом режиме .. потому что это сбивает с толку пользователей, если экран остается черным ...

привет

ОБНОВЛЕНИЕ: по запросу мой код

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.webViewCon = [[[WebViewController alloc] initWithNibName:@"WebView_iPhone" bundle:[NSBundle mainBundle]] autorelease];

    application.applicationIconBadgeNumber = 0;
    [window addSubview:[webViewCon view]];
    [self.window makeKeyAndVisible];

    // register for push
    NSLog(@"Registering for push notifications...");    
   [[UIApplication sharedApplication] 
     registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge | 
      UIRemoteNotificationTypeSound)];

    return YES;
}

А потом в didRegisterForRemoteNotificationsWithDeviceToken

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
    NSLog(@"%@",str);

    // get token & udidi
    NSString* newToken = [deviceToken description];
    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""]; 
    NSString *udid = [UIDevice currentDevice].uniqueIdentifier;

    // send request to server to save token
    NSString *urlString = [NSString stringWithFormat:@"https://my.server.com/service/token?token=%@&udid=%@",newToken, udid];

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

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [url release];

    NSURLResponse *response;
    [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
}

и в моем WebViewController.m

- (void)viewDidLoad
{
    // create and send POST request
    NSURL *url = [NSURL URLWithString:myUrlAddress];
    NSString *udid = [UIDevice currentDevice].uniqueIdentifier;
    NSString *requestString = [NSString stringWithFormat:@"udid=%@", udid];
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
    NSMutableURLRequest *requestObj = [[NSMutableURLRequest alloc] initWithURL:url];
    [requestObj setHTTPMethod:@"POST"];
    [requestObj setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [requestObj setHTTPBody: requestData];
    NSURLResponse *response;
    NSError *err;
    [NSURLConnection sendSynchronousRequest: requestObj returningResponse:&response error:&err];

    // set delegate
    webView.delegate = self;

    // set backgroundcolor
    [webView setOpaque:NO];
    [webView setBackgroundColor:RGB(154, 148, 131)];

    // check internet and load
    NetworkStatus currentStatus = [[Reachability reachabilityForInternetConnection] 
                               currentReachabilityStatus];
    if(currentStatus != NotReachable) {
        //Load the request in the UIWebView.
        [webView loadRequest:requestObj];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"No Connection" 
                          message:@"Check your Wi-Fi connection and restart the App." 
                          delegate:self
                          cancelButtonTitle:nil 
                          otherButtonTitles:@"Ok", nil];
        [alert show];
        [alert release];
    }
    // prevent scrolling up & down
    [[[webView subviews] lastObject] setScrollEnabled:NO];

   [super viewDidLoad];
}

надеюсь, что это поможет ... может ли Reachabilit также стать проблемой?

С уважением, читаем

Ответы [ 3 ]

2 голосов
/ 22 февраля 2012

Регистрация уведомлений в AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions и

Попробуйте реализовать эти методы,

// one of these will be called after calling -registerForRemoteNotifications
- (void)application:(UIApplication *)application  
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
- (void)application:(UIApplication *)application 
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:
(NSDictionary *)userInfo
1 голос
/ 22 февраля 2012

Согласно developer.apple.com , registerForRemoteNotificationTypes IS асинхронный:

Когда вы отправляете это сообщение, устройство инициирует процесс регистрации с помощью Apple Push Service.В случае успеха делегат приложения получает токен устройства в приложении: didRegisterForRemoteNotificationsWithDeviceToken: method;если регистрация не удалась, делегат уведомляется через приложение: didFailToRegisterForRemoteNotificationsWithError: method.

Может быть, вы занимаете много времени в ответных вызовах делегата?

1 голос
/ 22 февраля 2012

Поместите ваш код в -(BOOL)application:didFinishLaunchingWithOptions:, и он должен работать нормально.

...