2015-11-30 4 views
0

У меня есть базовое приложение для веб-просмотра, которое работает правильно и получает уведомления об отправке основного текста с Parse.com, но не может понять, как заставить его открыть URL-адрес.Приложение iOS Webview, как открыть JSON Parse Push Notification в Webview?

Я хочу, чтобы отправить JSON толчок уведомление от Parse.com как что-то вроде этого и он открыть указанный URL в моем WebView приложения:

EDIT ** Новый выпуск у меня сейчас я» m не удается открыть URL-адрес в веб-браузере, если приложение находится в фоновом режиме или на переднем плане.

В настоящее время, если приложение находится в фоновом режиме и вы используете уведомление, оно просто приведет приложение на передний план, но не перезагрузит новый URL. И если приложение находится на переднем плане, уведомление принимается как предупреждение, и при нажатии «ОК» действие не происходит.

{ 
"alert": "Push title goes here", 
"url": "http://www.google.com" 
} 

В моей WebBrowserAppDelegate.m У меня есть это:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
     [Parse setApplicationId:@"XXX" 
         clientKey:@"XXX"]; 

     // Register for Push Notitications 
     UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert | 
                 UIUserNotificationTypeBadge | 
                 UIUserNotificationTypeSound); 
     UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes 
                       categories:nil]; 
     [application registerUserNotificationSettings:settings]; 
     [application registerForRemoteNotifications]; 

     // Override point for customization after application launch. 

     self.window.rootViewController = self.viewController; 
     [self.window makeKeyAndVisible]; 

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; 
    NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]; 
    NSString *pushURL = [notificationPayload objectForKey:@"url"]; 

    if (notification) { 
     NSDictionary *aDict=[NSDictionary dictionaryWithObject: pushURL forKey:@"urlToLoad"]; 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadRequestFromAppDel" object:Nil userInfo:aDict]; 
    } 

    return YES; 
    } 
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { 
     [PFPush handlePush:userInfo]; 
     } 

И в моем WebBrowserViewController.m У меня есть это:

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

     NSAssert(self.back, @"Unconnected IBOutlet 'back'"); 
     NSAssert(self.forward, @"Unconnected IBOutlet 'forward'"); 
     NSAssert(self.refresh, @"Unconnected IBOutlet 'refresh'"); 
     NSAssert(self.stop, @"Unconnected IBOutlet 'stop'"); 
     NSAssert(self.webView, @"Unconnected IBOutlet 'webView'"); 

     self.webView.delegate = self; 
     self.webView.scalesPageToFit = YES; 
     NSURL* url = [NSURL URLWithString:@"http://www.mywebsite.com"]; 
     NSURLRequest* request = [NSURLRequest requestWithURL:url]; 
     [self.webView loadRequest:request]; 
     [self updateButtons]; 
    } 

- (void)LoadRequestFromAppDel: (NSNotification*)aNotif 
{ 
    NSString *aStrUrl=[[aNotif userInfo] objectForKey:@"urlToLoad"]; 
    NSURL* pushurl = [NSURL URLWithString:aStrUrl]; 
    NSURLRequest* requestObj = [NSURLRequest requestWithURL:pushurl]; 
    [self.webView loadRequest:requestObj]; 
    [self updateButtons]; 
} 

Заранее спасибо за любую помощь !

+0

вам нужно перехватить ответ от разбора. Я покажу вам одну секунду. – Loxx

ответ

1

Это, как вы перехватывать удаленный толчок с помощью parse.com:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; 
    NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]; 
    NSString *productId = [notificationPayload objectForKey:@"p"]; 

    if (notification) { 
    //this will only trigger when the app has been opend from a remote PUSH notification!! 

     [self application:application didReceiveRemoteNotification:(NSDictionary*)notification]; 
     _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
     [_window makeKeyAndVisible]; 

     _customRootViewController = [EZPUSHEXAMPLENavigationController new]; 
     [_customRootViewController setNavigationBarHidden:true]; 
     [self.window setRootViewController:_customRootViewController]; 

     if ([PFUser currentUser] == nil) { 
      [self registerForNotifications:application launchOptions:launchOptions]; 
      EZPUSHEXAMPLEPreSplashViewController * splashScreen = [[EZPUSHEXAMPLEPreSplashViewController alloc] init]; 
      [_customRootViewController setViewControllers:@[splashScreen] animated:TRUE]; 
     } else { 
      EZPUSHEXAMPLEPreSplashViewController * splashScreen = [[EZPUSHEXAMPLEPreSplashViewController alloc] init]; 
      EZPUSHEXAMPLECustomTabBarController * mvc = [[EZPUSHEXAMPLECustomTabBarController alloc] init]; 
      [mvc.navigationController.navigationBar setTranslucent:TRUE]; 
      [mvc.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]]; 
      [(EZPUSHEXAMPLEFeedViewController*)[[[[mvc viewControllers] objectAtIndex:0] viewControllers] objectAtIndex:0] setProductId:productId]; 
      [_customRootViewController setViewControllers:@[splashScreen, mvc] animated:TRUE]; 
    } 
     return YES; 
    } else { 
     _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
     [_window makeKeyAndVisible]; 
     _customRootViewController = [EZPUSHEXAMPLENavigationController new]; 
     [_customRootViewController setNavigationBarHidden:true]; 
     [self.window setRootViewController:_customRootViewController]; 
     if ([PFUser currentUser] == nil) { 
      [self registerForNotifications:application launchOptions:launchOptions]; 
      EZPUSHEXAMPLEPreSplashViewController * splashScreen = [[EZPUSHEXAMPLEPreSplashViewController alloc] init]; 
      [_customRootViewController setViewControllers:@[splashScreen] animated:TRUE]; 
     } else { 
      EZPUSHEXAMPLEPreSplashViewController * splashScreen = [[EZPUSHEXAMPLEPreSplashViewController alloc] init]; 
      EZPUSHEXAMPLECustomTabBarController * mvc = [[EZPUSHEXAMPLECustomTabBarController alloc] init]; 
      [mvc.navigationController.navigationBar setTranslucent:TRUE]; 
      [mvc.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]]; 
      [_customRootViewController setViewControllers:@[splashScreen, mvc] animated:TRUE]; 
     } 
     return YES; 
    } 
} 

В приведенном выше примере, в вашем случае, в первой части «если (уведомление)» триггер, вы бы инициализировать ваш пользовательский контроллер веб-представления, а затем представите его или установите его или нажмите на него, как бы вы ни хотели, это проверяется как работающий прямо сейчас, используя триггеры кода Parse Cloud для событий push-уведомлений, когда APP ПОЛНОСТЬЮ ЗАКРЫТА ПОЛЬЗОВАТЕЛЕМ. Таким образом, это означает, что это уведомление даже срабатывает в полностью закрытом приложении. Я не знаю, будет ли это работать, когда приложение находится в фоновом режиме, но это будет работать, когда оно будет полностью закрыто.

+0

Спасибо за ответ! Теперь, чтобы проверить это сейчас, извините, если это глупый вопрос, но я бы просто отказался от этого в моем WebBrowserAppDelegate.m под тем, где я установил свой Parse ApplicationId и ClientKey? – AJ47

+0

в основном, да, только часть if/then и объявления перед частями if/then, а затем убедитесь, что вы «возвращаете правильные ключи» из push-словаря, в моем случае «p» является настраиваемым полем в словарь, который вытесняется из облачного кода. – Loxx

+0

И, кроме того, есть довольно интенсивное приведение типов к методам, которые я использую там. Вы не должны использовать подобные методы в своем экземпляре, скорее всего, только потому, что сейчас вы сбиваете с толку вас, скорее всего, из-за того, что вы отправляете значение строки пользовательского объекта в userinfodictionary в JSON отталкивает вас от Parse. Затем вы перехватываете это сообщение и просматриваете свое настроенное значение, затем выполняете работу или вносите изменения в то, что вы хотите, чтобы ваше действие основывалось на этом настраиваемом строковом значении. – Loxx

Смежные вопросы