public override void DetectWebViewLoadFinishedEvent(UIApplication application, NSDictionary launchOptions)
        {
            UIApplicationState applicationState = application.ApplicationState;

            ((UnityUI_iOSViewController_UIWebView)MainViewController()).webView.LoadFinished += delegate {
                                #if DEBUG
                log("************** WEBVIEW LOAD FINISHED");
                                #endif

                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    UIView.AnimationsEnabled = true;                      //enable again animation in all view  (see UnityUI_iOSViewController_UIWebView#loadWebView for details)
                }

                // inform other weak delegates (if exist) about the web view finished event
                IPhoneServiceLocator.WebViewLoadingFinished(applicationState, launchOptions);

                // The NSDictionary options variable would contain any notification data if the user clicked the 'view' button on the notification
                // to launch the application.
                // This method processes these options from the FinishedLaunching.
                processLaunchOptions(launchOptions, true, applicationState);

                // Processing extra data received when launched externally (using custom scheme url)
                processLaunchData();
            };
        }
Example #2
0
        /// <summary>
        /// Processes the local notification.
        /// </summary>
        /// <param name="application">Application.</param>
        /// <param name="localNotification">Local notification.</param>
        private void ProcessLocalNotification(UIApplicationState applicationState, UILocalNotification localNotification)
        {
            if (localNotification != null)
            {
#if DEBUG
                log("******* Local NOTIFICATION received");
#endif

                if (applicationState == UIApplicationState.Active)
                {
                    // we need to manually process the notification while application is running.
#if DEBUG
                    log("******* Application is running, manually showing notification");
#endif
                    this.UpdateApplicationIconBadgeNumber((int)localNotification.ApplicationIconBadgeNumber);
                    this.PlayNotificationSound(localNotification.SoundName);
                    this.ShowNotificationAlert("Notification", localNotification.AlertBody);
                }

                NotificationData notificationData = new NotificationData();
                notificationData.AlertMessage = localNotification.AlertBody;
                notificationData.Badge        = (int)localNotification.ApplicationIconBadgeNumber;
                notificationData.Sound        = localNotification.SoundName;

                if (localNotification.UserInfo != null)
                {
                    Dictionary <String, Object> customDic = IPhoneUtils.GetInstance().ConvertToDictionary(new NSMutableDictionary(localNotification.UserInfo));
                    notificationData.CustomDataJsonString = IPhoneUtils.GetInstance().JSONSerialize(customDic);
                }

                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.OnLocalNotificationReceived", notificationData);
            }
        }
Example #3
0
        /*
         * public override void DecidePolicy (WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
         * {
         *      Console.WriteLine ("**** DecidePolicy****: " + navigationAction.Request);
         *
         *      webView.LoadRequest (navigationAction.Request);  // testing, it blocks the request load
         *
         * }
         */

        public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
        {
                        #if DEBUG
            SystemLogger.Log(SystemLogger.Module.GUI, "AppverseWKNavigationDelegate ************** WEBVIEW LOAD FINISHED");
                        #endif
            if (_appDelegate != null && _application != null)
            {
                UIApplicationState applicationState = _application.ApplicationState;

                // inform other weak delegates (if exist) about the web view finished event
                IPhoneServiceLocator.WebViewLoadingFinished(applicationState, _launchOptions);

                // The NSDictionary options variable would contain any notification data if the user clicked the 'view' button on the notification
                // to launch the application.
                // This method processes these options from the FinishedLaunching.
                _appDelegate.processLaunchOptions(_launchOptions, true, applicationState);

                // Processing extra data received when launched externally (using custom scheme url)
                _appDelegate.processLaunchData();
            }
            else
            {
                                #if DEBUG
                SystemLogger.Log(SystemLogger.Module.GUI, "AppverseWKNavigationDelegate  ************** Application Delegate is not accessible. Stop processing notifications and/or launch data");
                                #endif
            }
        }
        /*
        [Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")]
        public void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) {
            // This method is part of iOS 7.0 new remote notification support.
            // This method is invoked if your Entitlements list the "remote-notification" background operation is set, and you receive a remote notification.
            // Upon completion, you must notify the operating system of the result of the method by invoking the provided callback.
            // Important: failure to call the provided callback method with the result code before this method completes will cause your application to be terminated.
            log ("DidReceiveRemoteNotification: processing data..." );
            processNotification(userInfo, false, application.ApplicationState);
        }
        */
        /// <summary>
        /// Processes the notification.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the remote notification</param>
        public static void processNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                #if DEBUG
                log ("******* Checking for PUSH NOTIFICATION data in launch options - fromFinishedLaunching="+fromFinishedLaunching+". application state: "+ applicationState);
                #endif
                if (options != null) {

                    if (fromFinishedLaunching) {
                        NSDictionary remoteNotif = (NSDictionary)options.ObjectForKey (UIApplication.LaunchOptionsRemoteNotificationKey);
                        ProcessRemoteNotification (remoteNotif, fromFinishedLaunching, applicationState);
                    } else {
                        ProcessRemoteNotification (options, fromFinishedLaunching, applicationState);
                    }

                } else {
                    #if DEBUG
                    log ("******* NO launch options");
                    #endif
                }
            } catch (System.Exception ex) {
                #if DEBUG
                log ("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                #endif
            }
        }
Example #5
0
        private void AvailabiltyListener_RideDetailsFound(object sender, AvailabilityListener.RideDetailsEventArgs e)
        {
            newRideDetails = e.RideDetails;

            alertNewRide = UIAlertController.Create("New Ride Request", $"New Trip to {e.RideDetails.DestinationAddress}", UIAlertControllerStyle.Alert);

            alertNewRide.AddAction(UIAlertAction.Create("Reject", UIAlertActionStyle.Cancel, null));

            UIAlertAction alertOk = UIAlertAction.Create("Accept", UIAlertActionStyle.Default, (args) => Accepted(e.RideDetails));

            alertNewRide.AddAction(alertOk);
            alertNewRide.PreferredAction = alertOk;
            PresentViewController(alertNewRide, true, null);

            UIApplicationState state = UIApplication.SharedApplication.ApplicationState;

            if (state == UIApplicationState.Active)
            {
                TriggerAlert();
            }
            else if (state == UIApplicationState.Background)
            {
                SendNotification(e.RideDetails);
            }
        }
Example #6
0
        private void UpdateSpeed()
        {
            while (true)
            {
                if (speeds.Count > 0)
                {
                    InvokeOnMainThread(delegate
                    {
                        UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
                        if (state == UIApplicationState.Active)
                        {
                            float speed = speeds.Dequeue();
                            Console.WriteLine("Speed Removed From queue");
                            DigitalSpeed.Text         = speed.ToString();
                            TopSpeedDigitalLabel.Text = maxSpeed.ToString();
                            if (showSpeed && speed <= 100)
                            {
                                CreateSpeedometerRound(speed, maxSpeed);
                            }
                        }
                    });
                }

                Thread.Sleep(500);
            }
        }
Example #7
0
        /*public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
         * {
         *      ProcessNotification(userInfo, false);
         * }*/

        void ProcessNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState appState)
        {
            // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
            if (null != options && options.ContainsKey(new NSString("aps")))
            {
                //Get the aps dictionary
                NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

                string alert = string.Empty;

                //Extract the alert text
                //NOTE: If you're using the simple alert by just specifying "  aps:{alert:"alert msg here"}  "
                //this will work fine.  But if you're using a complex alert with Localization keys, etc.,
                //your "alert" object from the aps dictionary will be another NSDictionary... Basically the
                //json gets dumped right into a NSDictionary, so keep that in mind
                if (aps.ContainsKey(new NSString("alert")))
                {
                    alert = (aps [new NSString("alert")] as NSString).ToString();

                    int tripid = -1;
                    if (aps.ContainsKey(new NSString("tripid")))
                    {
                        tripid = (aps [new NSString("tripid")] as NSNumber).IntValue;
                    }


                    //If this came from the ReceivedRemoteNotification while the app was running,
                    // we of course need to manually process things like the sound, badge, and alert.
                    if (!fromFinishedLaunching)
                    {
                        //Manually show an alert
                        if (!string.IsNullOrEmpty(alert))
                        {
                            if (NotificationAlertView != null)
                            {
                                NotificationAlertView.DismissWithClickedButtonIndex(0, false);
                            }

                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "notifications", "alert", null).Build());

                            NotificationAlertView = new UIAlertView("Notification", alert, null, "OK", null);
                            NotificationAlertView.Show();
                        }
                    }
                }

                if (aps.ContainsKey(new NSString("content-available")))
                {
                    GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "notifications", "content-available", null).Build());
                    //TODO get list of times to send location
                    //backgroundTaskId = UIApplication.SharedApplication.BeginBackgroundTask( () => {});
                    DurationToSendLocation_Sec = (aps [new NSString("content-available")] as NSNumber).IntValue;
                    //NSTimer locationTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (60), delegate {
                    MonitorLocation(appState);
                    //});
                }
            }
        }
        private void ProcessLocalNotification(UILocalNotification notification, UIApplicationState state)
        {
            GMBLCommunication communication = GMBLCommunicationManager.CommunicationForLocalNotification(notification);

            if (communication != null)
            {
                UIApplication.SharedApplication.CancelLocalNotification(notification);
                //[self storeCommunication:communication];
                Debug.WriteLine(String.Format("ProcessLocalNotification communication {0}", communication));
            }
        }
        public static void WebViewLoadingFinished(UIApplicationState applicationState, NSDictionary options)
        {
            // informs the UIApplication Weak delegates (if any) about the web view loading finished  event
            var tsEnumerator = typedServices.GetEnumerator();

            while (tsEnumerator.MoveNext())
            {
                var typedService = tsEnumerator.Current;
                if (typedService.Value is IWeakDelegateManager)
                {
                    (typedService.Value as IWeakDelegateManager).WebViewLoadingFinished(applicationState, options);
                }
            }
        }
Example #10
0
        public async Task HandleMessageReceivedAsync(UIApplicationState applicationState, NSDictionary userInfo)
        {
            var data = NSJsonSerialization.Serialize(userInfo, 0, out var error);
            var json = data.ToString();

            if (applicationState == UIApplicationState.Active)
            {
                _pushNotificationsService.HandleForegroundNotification(json);
            }
            else
            {
                await _pushNotificationsService.HandleNotificationTappedAsync(json);
            }
        }
Example #11
0
        public void SoundUpdates()
        {
            //This function is threaded from the main thread.
            //Used to constantly update the sound levels
            if (debugPrint)
            {
                Console.WriteLine("Sounds Update Thread");
            }

            //If the sound is not started the thread will end
            while (sound.started)
            {
                //Gets the sound level
                float level = sound.workVolume();

                //If the application is in the foreground then the progress bar in the main thread will be updated
                InvokeOnMainThread(delegate
                {
                    UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
                    if (state == UIApplicationState.Active)
                    {
                        SoundBar.Progress = level;
                    }
                });

                //Time delay, uses a variable, power saving mode may change this to update less
                Thread.Sleep(AudioThreadSleep);

                if (level > .9)
                {
                    if (debugPrint)
                    {
                        Console.WriteLine("Shot Found");
                    }
                    if (debugPrint)
                    {
                        Thread.Sleep(1500);
                    }
                }
            }
        }
Example #12
0
        private void UpdateAnnotation()
        {
            //Removes all current overlays

            while (true)
            {
                CLLocationCoordinate2D[] dataArray = LocationFinderManager.data.GetAndRemoveData();
                if (dataArray.Length > 1)
                {
                    InvokeOnMainThread(delegate
                    {
                        UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
                        if (state == UIApplicationState.Active)
                        {
                            MapView.AddOverlay(MKPolyline.FromCoordinates(dataArray));
                        }
                    });
                }
                Thread.Sleep(1000);
            }
        }
Example #13
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
                        #if DEBUG
            log("FinishedLaunching with NSDictionary");
                        #endif
            //MainAppWindow ().AddSubview (MainViewController ().View);
            //MainAppWindow ().MakeKeyAndVisible ();

            window = new UIWindow(UIScreen.MainScreen.Bounds);

            viewController            = new UnityUI_iOSViewController();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible();

            // do not detect data types automatically (phone links, etc)
            MainViewController().webView.DataDetectorTypes = UIDataDetectorType.None;

            // remove all cache content (testing purposes)
            //NSUrlCache.SharedCache.RemoveAllCachedResponses();

            InitializeUnity();

            UIApplicationState applicationState = application.ApplicationState;

            MainUIWebView().LoadFinished += delegate {
#if DEBUG
                log("************** WEBVIEW LOAD FINISHED");
#endif
                // The NSDictionary options variable would contain any notification data if the user clicked the 'view' button on the notification
                // to launch the application.
                // This method processes these options from the FinishedLaunching, as well as the ReceivedRemoteNotification methods.
                processNotification(launchOptions, true, applicationState);

                // Processing extra data received when launched externally (using custom scheme url)
                processLaunchData();
            };

            return(true);
        }
Example #14
0
        private void ProcessNotification(UIApplicationState appState, NSDictionary options, bool fromFinishedLaunching)
        {
            // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
            if (null != options && options.ContainsKey(new NSString("aps")))
            {
                //Get the aps dictionary
                NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

                if (appState == UIApplicationState.Active)
                {
                    if (aps.ContainsKey(new NSString("alert")))
                    {
                        var alert = (aps[new NSString("alert")] as NSString).ToString();
                        //Manually show an alert
                        if (!string.IsNullOrEmpty(alert))
                        {
                            UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
                            avAlert.Show();
                        }
                    }
                }
                else
                {
                    if (options.ContainsKey(new NSString("clueId")))
                    {
                        var clueId = (options.ObjectForKey(new NSString("clueId")) as NSString).ToString();

                        if (!string.IsNullOrEmpty(clueId))
                        {
                            var navigationService = IoC.Get <INavigationService>();
                            // TODO Bootcamp: Navigate to details of clue
                            //navigationService.For<>()
                            //.WithParam()
                            //.Navigate(false);
                        }
                    }
                }
            }
        }
        // Apple Notifications
        public void HandleNotification(NSDictionary payload, UIApplicationState state)
        {
            if (state != UIApplicationState.Active)
            {
                // Standard APNS contents
                if (payload.ContainsKey((NSString)"aps"))
                {
                    // HOUSTON We have a push notification!
                    Util.Debug("HOUSTON We have a apple push notification!");
                    var nsPush = (NSDictionary)payload[(NSString)"aps"];
                    var push   = Util.ConvertToDictionary(nsPush);

                    if (push.ContainsKey("badge"))
                    {
                        int b;
                        if (Int32.TryParse(push["badge"].ToString(), out b))
                        {
                            Util.RunOnUIThread(() => { UIApplication.SharedApplication.ApplicationIconBadgeNumber = b; });
                        }
                    }
                }
            }
        }
Example #16
0
        /// <summary>
        /// Processes the notification.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the remote notification</param>
        void processNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                                #if DEBUG
                log("******* PROCESSING NOTIFICATION fromFinishedLaunching=" + fromFinishedLaunching + ". application state: " + applicationState);
                                #endif
                if (options != null)
                {
                    // LOCAL NOTIFICATIONS

                    UILocalNotification localNotif = (UILocalNotification)options.ObjectForKey(UIApplication.LaunchOptionsLocalNotificationKey);
                    this.ProcessLocalNotification(applicationState, localNotif);

                    // REMOTE NOTIFICATIONS
                    if (fromFinishedLaunching)
                    {
                        NSDictionary remoteNotif = (NSDictionary)options.ObjectForKey(UIApplication.LaunchOptionsRemoteNotificationKey);
                        this.ProcessRemoteNotification(remoteNotif, fromFinishedLaunching, applicationState);
                    }
                    else
                    {
                        this.ProcessRemoteNotification(options, fromFinishedLaunching, applicationState);
                    }
                }
                else
                {
                                        #if DEBUG
                    log("******* NO launch options");
                                        #endif
                }
            } catch (System.Exception ex) {
                                #if DEBUG
                log("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                                #endif
            }
        }
Example #17
0
        private void ProcessRemoteNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            //Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
            if (options!=null && options.ContainsKey(new NSString("aps")))
            {
            #if DEBUG
                log (" ******* PROCESSING REMOTE NOTIFICATION Notification Payload received");
            #endif
                NotificationData notificationData = new NotificationData ();
                string alert = string.Empty;
                string sound = string.Empty;
                int badge = -1;

                try {
                    //Get the aps dictionary
                    NSDictionary aps = options.ObjectForKey (new NSString ("aps")) as NSDictionary;

                //Extract the alert text
                //NOTE: Just for the simple alert specified by "  aps:{alert:"alert msg here"}  "
                //      For complex alert with Localization keys, etc., the "alert" object from the aps dictionary
                //      will be another NSDictionary... Basically the json gets dumped right into a NSDictionary, so keep that in mind
                    if (aps.ContainsKey (new NSString ("alert"))) {
                        string alertType = "undefined";
                        if (aps[new NSString ("alert")].GetType () == typeof(NSString)) {
                            alert = (aps [new NSString ("alert")] as NSString).ToString ();
                            alertType = "NSString";
                        } else if (aps [new NSString ("alert")].GetType () == typeof(NSDictionary)) {
                            NSDictionary alertNSDictionary = aps.ObjectForKey (new NSString ("alert")) as NSDictionary;
                            alertType = "NSDictionary";
                            // We only get "body" key from that dictionary
                            if (alertNSDictionary.ContainsKey (new NSString ("body"))
                                    && (alertNSDictionary[new NSString ("body")].GetType () == typeof(NSString))) {
                                alert = (alertNSDictionary [new NSString ("body")] as NSString).ToString ();
                            }
                        }

                        #if DEBUG
                        log ("******* PROCESSING NOTIFICATION Notification Payload contains an alert message. Type [" + alertType + "]");
                        #endif
                }

                //Extract the sound string
                    if (aps.ContainsKey (new NSString ("sound")) && (aps [new NSString ("sound")].GetType() == typeof(NSString))) {
                        sound = (aps [new NSString ("sound")] as NSString).ToString ();
                        #if DEBUG
                    log ("******* PROCESSING NOTIFICATION Notification Payload contains sound");
                        #endif
                }

                //Extract the badge
                    if (aps.ContainsKey (new NSString ("badge")) && (aps [new NSString ("badge")].GetType() == typeof(NSObject))) {
                        string badgeStr = (aps [new NSString ("badge")] as NSObject).ToString ();
                        int.TryParse (badgeStr, out badge);
                        #if DEBUG
                    log ("******* PROCESSING NOTIFICATION Notification Payload contains a badge number: " + badge);
                        #endif
                }

                //If this came from the ReceivedRemoteNotification while the app was running,
                // we of course need to manually process things like the sound, badge, and alert.
                    if (!fromFinishedLaunching && applicationState == UIApplicationState.Active) {

                        #if DEBUG
                    log ("******* PROCESSING NOTIFICATION app was running, so manually showing notification");
                        #endif

                    UIRemoteNotificationType enabledRemoteNotificationTypes = UIApplication.SharedApplication.EnabledRemoteNotificationTypes;

                    bool alertEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Alert) == UIRemoteNotificationType.Alert);
                    bool soundEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Sound) == UIRemoteNotificationType.Sound);
                    bool badgeEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Badge) == UIRemoteNotificationType.Badge);

                        #if DEBUG
                    log ("******* PROCESSING NOTIFICATION types enabled: alert[" + alertEnabled+"], sound[" + soundEnabled + "], badge[" + badgeEnabled+ "]");
                        #endif
                    //Manually set the badge in case this came from a remote notification sent while the app was open
                    if (badgeEnabled) {
                            this.UpdateApplicationIconBadgeNumber (badge);
                    }

                    //Manually play the sound
                        if (soundEnabled) {
                            this.PlayNotificationSound (sound);
                    }

                    //Manually show an alert
                        if (alertEnabled) {
                            this.ShowNotificationAlert ("Notification", alert);
                    }
                }

                    Dictionary<String,Object> customDic = IPhoneUtils.GetInstance ().ConvertToDictionary (new NSMutableDictionary (options));
                    customDic.Remove ("aps"); // it is not needed to pass the "aps" (notification iOS data) inside the "custom data json string"
                    notificationData.CustomDataJsonString = IPhoneUtils.GetInstance ().JSONSerialize (customDic);

                } catch (System.Exception ex) {
                    #if DEBUG
                    log (" ******* Unhanlded exception processing notification payload received. Exception message: " + ex.Message);
                    #endif
                } finally {

                notificationData.AlertMessage = alert;
                notificationData.Badge = badge;
                notificationData.Sound = sound;

                    IPhoneUtils.GetInstance ().FireUnityJavascriptEvent ("Unity.OnRemoteNotificationReceived", notificationData);
                }

            } else {
            #if DEBUG
                log (" ******* NO Notification Payload received");
            #endif
            }
        }
Example #18
0
        /// <summary>
        /// Processes the notification.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the remote notification</param>
        void processNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                #if DEBUG
            log ("******* PROCESSING NOTIFICATION fromFinishedLaunching="+fromFinishedLaunching+". application state: "+ applicationState);
                #endif
                if (options != null) {

                // LOCAL NOTIFICATIONS

                    UILocalNotification localNotif = (UILocalNotification)options.ObjectForKey (UIApplication.LaunchOptionsLocalNotificationKey);
                    this.ProcessLocalNotification (applicationState, localNotif);

                // REMOTE NOTIFICATIONS
                    if (fromFinishedLaunching) {
                        NSDictionary remoteNotif = (NSDictionary)options.ObjectForKey (UIApplication.LaunchOptionsRemoteNotificationKey);
                        this.ProcessRemoteNotification (remoteNotif, fromFinishedLaunching, applicationState);
                } else {
                        this.ProcessRemoteNotification (options, fromFinishedLaunching, applicationState);
                }

            } else {
                    #if DEBUG
                log ("******* NO launch options");
                    #endif
                }
            } catch (System.Exception ex) {
                #if DEBUG
                log ("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                #endif
            }
        }
Example #19
0
        /// <summary>
        /// Processes the local notification.
        /// </summary>
        /// <param name="application">Application.</param>
        /// <param name="localNotification">Local notification.</param>
        private void ProcessLocalNotification(UIApplicationState applicationState, UILocalNotification localNotification)
        {
            if(localNotification != null) {
            #if DEBUG
                log ("******* Local NOTIFICATION received");
            #endif

                if (applicationState == UIApplicationState.Active)
                {
                    // we need to manually process the notification while application is running.
            #if DEBUG
                    log ("******* Application is running, manually showing notification");
            #endif
                    this.UpdateApplicationIconBadgeNumber(localNotification.ApplicationIconBadgeNumber);
                    this.PlayNotificationSound(localNotification.SoundName);
                    this.ShowNotificationAlert("Notification", localNotification.AlertBody);
                }

                NotificationData notificationData = new NotificationData();
                notificationData.AlertMessage = localNotification.AlertBody;
                notificationData.Badge = localNotification.ApplicationIconBadgeNumber;
                notificationData.Sound = localNotification.SoundName;

                if(localNotification.UserInfo != null) {
                    Dictionary<String,Object> customDic = IPhoneUtils.GetInstance().ConvertToDictionary(new NSMutableDictionary(localNotification.UserInfo));
                    notificationData.CustomDataJsonString = IPhoneUtils.GetInstance().JSONSerialize(customDic);
                }

                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.OnLocalNotificationReceived", notificationData);
            }
        }
		public virtual void WebViewLoadingFinished (UIApplicationState applicationState, NSDictionary options)
		{
			SystemLogger.Log ("WebViewLoadingFinished event received. Override this method if you need to handle this event in the Appverse module");
		}
Example #21
0
        /// <summary>
        /// Processes any received launch options.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the special launch options</param>
        public void processLaunchOptions(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                                #if DEBUG
                log("******* Checking launch optioins (if available) fromFinishedLaunching=" + fromFinishedLaunching + ". application state: " + applicationState);
                                #endif
                if (options != null)
                {
                    // LOCAL NOTIFICATIONS

                    UILocalNotification localNotif = (UILocalNotification)options.ObjectForKey(UIApplication.LaunchOptionsLocalNotificationKey);
                    this.ProcessLocalNotification(applicationState, localNotif);
                }
                else
                {
                                        #if DEBUG
                    log("******* NO launch options");
                                        #endif
                }
            } catch (System.Exception ex) {
                                #if DEBUG
                log("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                                #endif
            }
        }
Example #22
0
        /// <summary>
        /// Processes any received launch options.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the special launch options</param>
        public void processLaunchOptions(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                #if DEBUG
                log ("******* Checking launch optioins (if available) fromFinishedLaunching="+fromFinishedLaunching+". application state: "+ applicationState);
                #endif
                if (options != null) {

                    // LOCAL NOTIFICATIONS

                    UILocalNotification localNotif = (UILocalNotification)options.ObjectForKey (UIApplication.LaunchOptionsLocalNotificationKey);
                    this.ProcessLocalNotification (applicationState, localNotif);

                } else {
                    #if DEBUG
                    log ("******* NO launch options");
                    #endif
                }
            } catch (System.Exception ex) {
                #if DEBUG
                log ("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                #endif
            }
        }
		public void WebViewLoadingFinished (UIApplicationState applicationState, NSDictionary options)
		{
			SystemLogger.Log (SystemLogger.Module.PLATFORM, "******************************************* Detected WebView Loading Finished (processing launch options, if any)");
			UIApplicationWeakDelegate.processNotification (options, true, applicationState);
		}
        public override void DidReceiveRemoteNotification(
            UIApplication application,
            NSDictionary userInfo,
            Action <UIBackgroundFetchResult> completionHandler)
        {
            UIApplicationState state = application.ApplicationState;

            if (state == UIApplicationState.Background ||
                (state == UIApplicationState.Inactive &&
                 !appIsStarting))
            {
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

                var    messageKey = new NSString("alert");
                string message    = null;
                if (aps.ContainsKey(messageKey))
                {
                    message = (aps[messageKey] as NSString).ToString();
                }

                ShowAlert(message);
            }
            else if (state == UIApplicationState.Inactive && appIsStarting)
            {
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

                var    messageKey = new NSString("alert");
                string message    = null;
                if (aps.ContainsKey(messageKey))
                {
                    message = (aps[messageKey] as NSString).ToString();
                }

                ShowAlert(message);
                // user tapped notification
                //completionHandler(UIBackgroundFetchResult.NewData);
            }
            else
            {
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

                var    messageKey = new NSString("alert");
                string message    = null;
                if (aps.ContainsKey(messageKey))
                {
                    message = (aps[messageKey] as NSString).ToString();
                }

                ShowAlert(message);
                // app is active
                //completionHandler(UIBackgroundFetchResult.NoData);
            }



            void ShowAlert(string message)
            {
                if (!string.IsNullOrEmpty(message))
                {
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        var alert = UIAlertController.Create(
                            "Notificación",
                            $"{message} {appIsStarting}",
                            UIAlertControllerStyle.Alert);

                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));

                        var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        while (vc.PresentedViewController != null)
                        {
                            vc = vc.PresentedViewController;
                        }

                        vc.ShowDetailViewController(alert, vc);
                    });
                }
            }
        }
		public override void WebViewLoadingFinished (UIApplicationState applicationState, NSDictionary options)
		{
			SystemLogger.Log (SystemLogger.Module.PLATFORM, "******************************************* Detected WebView Loading Finished (processing launch options, if any)");
			AbstractPushNotifications.processNotification (options, true, applicationState);
		}
Example #26
0
        /*
         * [Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")]
         * public void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) {
         *      // This method is part of iOS 7.0 new remote notification support.
         *      // This method is invoked if your Entitlements list the "remote-notification" background operation is set, and you receive a remote notification.
         *      // Upon completion, you must notify the operating system of the result of the method by invoking the provided callback.
         *      // Important: failure to call the provided callback method with the result code before this method completes will cause your application to be terminated.
         *      log ("DidReceiveRemoteNotification: processing data..." );
         *      processNotification(userInfo, false, application.ApplicationState);
         * }
         */


        /// <summary>
        /// Processes the notification.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the remote notification</param>
        public static void processNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            try {
                                #if DEBUG
                log("******* Checking for PUSH NOTIFICATION data in launch options - fromFinishedLaunching=" + fromFinishedLaunching + ". application state: " + applicationState);
                                #endif
                if (options != null)
                {
                    if (fromFinishedLaunching)
                    {
                        NSDictionary remoteNotif = (NSDictionary)options.ObjectForKey(UIApplication.LaunchOptionsRemoteNotificationKey);
                        ProcessRemoteNotification(remoteNotif, fromFinishedLaunching, applicationState);
                    }
                    else
                    {
                        ProcessRemoteNotification(options, fromFinishedLaunching, applicationState);
                    }
                }
                else
                {
                                        #if DEBUG
                    log("******* NO launch options");
                                        #endif
                }
            } catch (System.Exception ex) {
                                #if DEBUG
                log("******* Unhandled exception when trying to process notification. fromFinishedLaunching[" + fromFinishedLaunching + "]. Exception message: " + ex.Message);
                                #endif
            }
        }
Example #27
0
        private void ProcessRemoteNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            //Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
            if (options != null && options.ContainsKey(new NSString("aps")))
            {
#if DEBUG
                log(" ******* PROCESSING REMOTE NOTIFICATION Notification Payload received");
#endif
                NotificationData notificationData = new NotificationData();
                string           alert            = string.Empty;
                string           sound            = string.Empty;
                int badge = -1;

                try {
                    //Get the aps dictionary
                    NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;


                    //Extract the alert text
                    //NOTE: Just for the simple alert specified by "  aps:{alert:"alert msg here"}  "
                    //      For complex alert with Localization keys, etc., the "alert" object from the aps dictionary
                    //      will be another NSDictionary... Basically the json gets dumped right into a NSDictionary, so keep that in mind
                    if (aps.ContainsKey(new NSString("alert")))
                    {
                        string alertType = "undefined";
                        if (aps[new NSString("alert")].GetType() == typeof(NSString))
                        {
                            alert     = (aps [new NSString("alert")] as NSString).ToString();
                            alertType = "NSString";
                        }
                        else if (aps [new NSString("alert")].GetType() == typeof(NSDictionary))
                        {
                            NSDictionary alertNSDictionary = aps.ObjectForKey(new NSString("alert")) as NSDictionary;
                            alertType = "NSDictionary";
                            // We only get "body" key from that dictionary
                            if (alertNSDictionary.ContainsKey(new NSString("body")) &&
                                (alertNSDictionary[new NSString("body")].GetType() == typeof(NSString)))
                            {
                                alert = (alertNSDictionary [new NSString("body")] as NSString).ToString();
                            }
                        }

                                                #if DEBUG
                        log("******* PROCESSING NOTIFICATION Notification Payload contains an alert message. Type [" + alertType + "]");
                                                #endif
                    }

                    //Extract the sound string
                    if (aps.ContainsKey(new NSString("sound")) && (aps [new NSString("sound")].GetType() == typeof(NSString)))
                    {
                        sound = (aps [new NSString("sound")] as NSString).ToString();
                                                #if DEBUG
                        log("******* PROCESSING NOTIFICATION Notification Payload contains sound");
                                                #endif
                    }

                    //Extract the badge
                    if (aps.ContainsKey(new NSString("badge")) && (aps [new NSString("badge")].GetType() == typeof(NSObject)))
                    {
                        string badgeStr = (aps [new NSString("badge")] as NSObject).ToString();
                        int.TryParse(badgeStr, out badge);
                                                #if DEBUG
                        log("******* PROCESSING NOTIFICATION Notification Payload contains a badge number: " + badge);
                                                #endif
                    }

                    //If this came from the ReceivedRemoteNotification while the app was running,
                    // we of course need to manually process things like the sound, badge, and alert.
                    if (!fromFinishedLaunching && applicationState == UIApplicationState.Active)
                    {
                                                #if DEBUG
                        log("******* PROCESSING NOTIFICATION app was running, so manually showing notification");
                                                #endif

                        UIRemoteNotificationType enabledRemoteNotificationTypes = UIApplication.SharedApplication.EnabledRemoteNotificationTypes;

                        bool alertEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Alert) == UIRemoteNotificationType.Alert);
                        bool soundEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Sound) == UIRemoteNotificationType.Sound);
                        bool badgeEnabled = ((enabledRemoteNotificationTypes & UIRemoteNotificationType.Badge) == UIRemoteNotificationType.Badge);

                                                #if DEBUG
                        log("******* PROCESSING NOTIFICATION types enabled: alert[" + alertEnabled + "], sound[" + soundEnabled + "], badge[" + badgeEnabled + "]");
                                                #endif
                        //Manually set the badge in case this came from a remote notification sent while the app was open
                        if (badgeEnabled)
                        {
                            this.UpdateApplicationIconBadgeNumber(badge);
                        }

                        //Manually play the sound
                        if (soundEnabled)
                        {
                            this.PlayNotificationSound(sound);
                        }

                        //Manually show an alert
                        if (alertEnabled)
                        {
                            this.ShowNotificationAlert("Notification", alert);
                        }
                    }


                    Dictionary <String, Object> customDic = IPhoneUtils.GetInstance().ConvertToDictionary(new NSMutableDictionary(options));
                    customDic.Remove("aps");                      // it is not needed to pass the "aps" (notification iOS data) inside the "custom data json string"
                    notificationData.CustomDataJsonString = IPhoneUtils.GetInstance().JSONSerialize(customDic);
                } catch (System.Exception ex) {
                                        #if DEBUG
                    log(" ******* Unhanlded exception processing notification payload received. Exception message: " + ex.Message);
                                        #endif
                } finally {
                    notificationData.AlertMessage = alert;
                    notificationData.Badge        = badge;
                    notificationData.Sound        = sound;

                    IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.OnRemoteNotificationReceived", notificationData);
                }
            }
            else
            {
#if DEBUG
                log(" ******* NO Notification Payload received");
#endif
            }
        }
Example #28
0
        /// <summary>
        /// Processes the notification.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <param name="fromFinishedLaunching">True if this method comes from the 'FinishedLaunching' delegated method</param>
        /// <param name="applicationState">The application state that received the remote notification</param>
        void processNotification(NSDictionary options, bool fromFinishedLaunching, UIApplicationState applicationState)
        {
            #if DEBUG
            log ("******* PROCESSING NOTIFICATION fromFinishedLaunching="+fromFinishedLaunching+". application state: "+ applicationState);
            #endif
            if(options != null) {

                // LOCAL NOTIFICATIONS

                UILocalNotification localNotif = (UILocalNotification) options.ObjectForKey(UIApplication.LaunchOptionsLocalNotificationKey);
                this.ProcessLocalNotification(applicationState, localNotif);

                // REMOTE NOTIFICATIONS
                if(fromFinishedLaunching) {
                    NSDictionary remoteNotif = (NSDictionary) options.ObjectForKey(UIApplication.LaunchOptionsRemoteNotificationKey);
                    this.ProcessRemoteNotification(remoteNotif, fromFinishedLaunching, applicationState);
                } else {
                    this.ProcessRemoteNotification(options, fromFinishedLaunching, applicationState);
                }

            } else {
            #if DEBUG
                log ("******* NO launch options");
            #endif
            }
        }
Example #29
0
 public void WebViewLoadingFinished(UIApplicationState applicationState, NSDictionary options)
 {
     SystemLogger.Log(SystemLogger.Module.PLATFORM, "******************************************* Detected WebView Loading Finished (processing launch options, if any)");
     UIApplicationWeakDelegate.processNotification(options, true, applicationState);
 }
		// Apple Notifications
		public void HandleNotification (NSDictionary payload, UIApplicationState state) {
			if (state != UIApplicationState.Active) {
				// Standard APNS contents
				if (payload.ContainsKey ((NSString) "aps")) {
					// HOUSTON We have a push notification!
					Util.Debug ("HOUSTON We have a apple push notification!");
					var nsPush = (NSDictionary) payload[(NSString)"aps"];
					var push = Util.ConvertToDictionary (nsPush);

					if (push.ContainsKey ("badge")) {
						int b;
						if (Int32.TryParse(push["badge"].ToString (), out b))
							Util.RunOnUIThread(() => { UIApplication.SharedApplication.ApplicationIconBadgeNumber = b; });
					}
				}
			}
		}
 public static void WebViewLoadingFinished(UIApplicationState applicationState, NSDictionary options)
 {
     // informs the UIApplication Weak delegates (if any) about the web view loading finished  event
     var tsEnumerator = typedServices.GetEnumerator ();
     while (tsEnumerator.MoveNext())
     {
         var typedService = tsEnumerator.Current;
         if (typedService.Value is IWeakDelegateManager) {
             (typedService.Value as IWeakDelegateManager).WebViewLoadingFinished (applicationState, options);
         }
     }
 }
Example #32
0
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler)
        {
            UIApplicationState state = UIApplication.SharedApplication.ApplicationState;

            completionHandler(UIBackgroundFetchResult.NewData);
        }
Example #33
0
        private void MonitorLocation(UIApplicationState appState)
        {
            if (CLLocationManager.LocationServicesEnabled)
            {
                LastSentLocationTime  = new DateTime(0);
                FirstSentLocationTime = new DateTime(0);
                Console.WriteLine("MONITOR LOCATION");

                GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "monitor location", null).Build());

                LocationManager = new CLLocationManager();
                LocationManager.DesiredAccuracy = 10;
                LocationManager.PausesLocationUpdatesAutomatically = false;

                LocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    CLLocation currentLocation  = e.Locations[e.Locations.Length - 1];
                    DateTime   locationDateTime = DateTime.SpecifyKind(currentLocation.Timestamp, DateTimeKind.Utc);

                    double timeremaining = UIApplication.SharedApplication.BackgroundTimeRemaining;

                    Console.WriteLine("LOCATION UPDATE - Time Remaining: " + timeremaining.ToString());

                    if (LastSentLocationTime.Ticks == 0)
                    {
                        Console.WriteLine("FIRST LOCATION SENT");
                        sendLocation(currentLocation);
                        FirstSentLocationTime = locationDateTime;
                        LastSentLocationTime  = locationDateTime;
                    }
                    else
                    {
                        var diffInSeconds = (locationDateTime - LastSentLocationTime).TotalSeconds;
                        if (diffInSeconds >= 10.0)
                        {
                            Console.WriteLine("LOCATION SENT");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "location sent", null).Build());
                            sendLocation(currentLocation);
                            LastSentLocationTime = locationDateTime;
                        }

                        var diffInSecondsFromFirst = (locationDateTime - FirstSentLocationTime).TotalSeconds;
                        if (diffInSecondsFromFirst >= 120)
                        {
                            Console.WriteLine("STOP MONITOR LOCATION");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "stop monitor location", null).Build());
                            if (LocationManager != null)
                            {
                                LocationManager.StopUpdatingLocation();
                                LocationManager.StopMonitoringSignificantLocationChanges();
                            }

                            LocationManager = null;
                        }
                    }
                };


                if (appState == UIApplicationState.Active)
                {
                    LocationManager.StartUpdatingLocation();
                }
                else
                {
                    LocationManager.StartMonitoringSignificantLocationChanges();
                }
            }
            else
            {
                Console.WriteLine("Location services not enabled");
            }
        }
		private static void SetLaunchState(UIApplicationState state, NSDictionary userInfo)
		{
			if (state != UIApplicationState.Active)
			{
				var appState = DonkyCore.Instance.GetService<IAppState>();
				appState.WasOpenedFromNotification = true;
				appState.LaunchingNotificationId = userInfo.GetValueOrDefault<string>("notificationId", null);
			}
		}