internal UITextAttributes(NSDictionary dict)
        {
            if (dict == null)
            {
                return;
            }

            NSObject val;

            if (dict.TryGetValue(UITextAttributesConstants.Font, out val))
            {
                Font = val as UIFont;
            }
            if (dict.TryGetValue(UITextAttributesConstants.TextColor, out val))
            {
                TextColor = val as UIColor;
            }
            if (dict.TryGetValue(UITextAttributesConstants.TextShadowColor, out val))
            {
                TextShadowColor = val as UIColor;
            }
            if (dict.TryGetValue(UITextAttributesConstants.TextShadowOffset, out val))
            {
                var value = val as NSValue;
                if (value != null)
                {
                    TextShadowOffset = value.UIOffsetValue;
                }
            }
        }
Example #2
0
        /// <summary>
        /// Used to handle application launch. Previously used <see cref="FinishedLaunching(UIApplication)" />
        /// which however does not support launch with arguments and is "technically" deprecated.
        /// </summary>
        /// <param name="application">UI Application.</param>
        /// <param name="launchOptions">Launch options.</param>
        /// <returns>Value indicating whether launch can be handled.</returns>
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            InitializationCompleted();
            var handled = false;

            if (launchOptions != null)
            {
                if (launchOptions.TryGetValue(UIApplication.LaunchOptionsUrlKey, out var urlObject))
                {
                    _preventSecondaryActivationHandling = true;
                    var url = (NSUrl)urlObject;
                    if (TryParseActivationUri(url, out var uri))
                    {
                        OnActivated(new ProtocolActivatedEventArgs(uri, ApplicationExecutionState.NotRunning));
                        handled = true;
                    }
                }
                else if (launchOptions.TryGetValue(UIApplication.LaunchOptionsShortcutItemKey, out var shortcutItemObject))
                {
                    _preventSecondaryActivationHandling = true;
                    var shortcutItem = (UIApplicationShortcutItem)shortcutItemObject;
                    OnLaunched(new LaunchActivatedEventArgs(ActivationKind.Launch, shortcutItem.Type));
                    handled = true;
                }
            }

            // default to normal launch
            if (!handled)
            {
                OnLaunched(new LaunchActivatedEventArgs());
            }
            return(true);
        }
Example #3
0
    private static Tuple <string, string> tryFindIODevice(NSDictionary dev)
    {
        NSDictionary node = dev;
        NSObject     child = null, IOCalloutDevice = null, IODialinDevice = null;

        while (node != null)
        {
            if (node.TryGetValue("IODialinDevice", out IODialinDevice) &&
                node.TryGetValue("IOCalloutDevice", out IOCalloutDevice))
            {
                break;
            }
            if (!node.TryGetValue("IORegistryEntryChildren", out child))
            {
                break;
            }
            if (child is NSArray)
            {
                node = (child as NSArray)[0] as NSDictionary;
            }
            else
            {
                node = child as NSDictionary;
            }
        }
        return(Tuple.Create(
                   (IODialinDevice as NSString)?.Content,
                   (IOCalloutDevice as NSString)?.Content
                   ));
    }
Example #4
0
 public TimedColor(NSDictionary timedColor)
 {
     if (timedColor.TryGetValue(PayloadKey.TimeStamp, out NSObject timeStamp) &&
         timedColor.TryGetValue(PayloadKey.ColorData, out NSObject colorData))
     {
         this.TimeStamp = (timeStamp as NSString).ToString();
         this.ColorData = colorData as NSData;
     }
     else
     {
         throw new Exception("Timed color dictionary doesn't have right keys!");
     }
 }
Example #5
0
		public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
		{
			NSObject aps, alert, payload;

			if(!userInfo.TryGetValue(new NSString("aps"), out aps))
				return;

			var apsHash = aps as NSDictionary;

			NotificationPayload payloadValue = null;
			if(apsHash.TryGetValue(new NSString("payload"), out payload))
			{
				payloadValue = JsonConvert.DeserializeObject<NotificationPayload>(payload.ToString());
				if(payloadValue != null)
				{
					MessagingCenter.Send(App.Instance, Shared.Messages.IncomingPayloadReceivedInternal, payloadValue);
				}
			}

			var badgeValue = apsHash.ObjectForKey(new NSString("badge"));

			if(badgeValue != null)
			{
				int count;
				if(int.TryParse(new NSString(badgeValue.ToString()), out count))
				{
					//UIApplication.SharedApplication.ApplicationIconBadgeNumber = count;
				}
			}

			if(apsHash.TryGetValue(new NSString("alert"), out alert))
			{
				alert.ToString().ToToast(ToastNotificationType.Info, "Incoming notification");
			}
		}
Example #6
0
        /// <summary>
        /// Checks the System's Environment Variable HIDIdleTime which is maintained by apple to register last Keyboard or Mouse Input
        /// </summary>
        /// <returns></returns>
        public static TimeSpan CheckIdleTime()
        {
            long     idlesecs = 0;
            int      iter     = 0;
            TimeSpan idleTime = TimeSpan.Zero;

            if (IOServiceGetMatchingServices(0, IOServiceMatching("IOHIDSystem"), ref iter) == 0)
            {
                int entry = IOIteratorNext(iter);
                if (entry != 0)
                {
                    IntPtr dictHandle;
                    if (IORegistryEntryCreateCFProperties(entry, out dictHandle, IntPtr.Zero, 0) == 0)
                    {
                        NSDictionary dict = (NSDictionary)MonoMac.ObjCRuntime.Runtime.GetNSObject(dictHandle);
                        NSObject     value;
                        dict.TryGetValue((NSString)"HIDIdleTime", out value);
                        if (value != null)
                        {
                            long nanoseconds = 0;
                            if (CFNumberGetValue(value.Handle, 4, out nanoseconds))
                            {
                                idlesecs = nanoseconds >> 30; // Shift To Convert from nanoseconds to seconds.
                                idleTime = DateTime.Now - DateTime.Now.AddSeconds(-idlesecs);
                            }
                        }
                    }
                    IOObjectRelease(entry);
                }
                IOObjectRelease(iter);
            }

            return(idleTime);
        }
Example #7
0
        // This method is invoked when the application has loaded its UI and its ready to run
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Console.WriteLine("something woke me up!");

            if (options != null)
            {
                NSObject launchedFromLocation;
                if (options.TryGetValue(UIApplication.LaunchOptionsLocationKey, out launchedFromLocation))
                {
                    if (((NSNumber)launchedFromLocation).BoolValue)
                    {
                        Console.WriteLine("Launched From Location Event");

                        // wrapper method to ensure the location manager is created
                        // in the case where the app was launched in the background
                        // due to a location update
                        LocationHelper.Initialize();
                    }
                }
            }

            window.AddSubview(locationTableController.View);

            window.MakeKeyAndVisible();

            return(true);
        }
Example #8
0
        /// <summary>
        /// Called when a userInfo is received.
        /// </summary>
        public override void DidReceiveUserInfo(WCSession session, NSDictionary <NSString, NSObject> userInfo)
        {
            var commandStatus = new CommandStatus(Command.TransferUserInfo, Phrase.Received)
            {
                TimedColor = new TimedColor(userInfo)
            };

            if (userInfo.TryGetValue(PayloadKey.IsCurrentComplicationInfo, out NSObject isComplicationInfoObject) &&
                isComplicationInfoObject is NSNumber isComplicationInfo && isComplicationInfo.BoolValue)
            {
                commandStatus.Command = Command.TransferCurrentComplicationUserInfo;

#if __WATCHOS__
                var server        = CLKComplicationServer.SharedInstance;
                var complications = server.ActiveComplications;
                if (complications != null && complications.Any())
                {
                    foreach (var complication in complications)
                    {
                        // Call this method sparingly. If your existing complication data is still valid,
                        // consider calling the extendTimeline(for:) method instead.
                        server.ReloadTimeline(complication);
                    }
                }
#endif
            }

            this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus);
        }
        public override bool WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
        {
            /*
            UILocalNotification tn = new UILocalNotification();
            tn.AlertBody = "WillFinishLaunching";
            UIApplication.SharedApplication.PresentLocationNotificationNow(tn);
            */

            if (launchOptions != null)
            {
                NSObject launchFromLocations;
                if(launchOptions.TryGetValue(UIApplication.LaunchOptionsLocationKey, out launchFromLocations))
                {
                    if(((NSNumber)launchFromLocations).BoolValue)
                    {
                        UILocalNotification ln = new UILocalNotification();
                        ln.AlertBody = "position changed!";
                        ln.AlertAction = "просмотреть";
                        UIApplication.SharedApplication.PresentLocationNotificationNow(ln);
                    }
                }
            }

            return true;
        }
Example #10
0
 // This method is invoked when the application has loaded its UI and its ready to run
 public override bool FinishedLaunching (UIApplication app, NSDictionary options)
 {
     Console.WriteLine ("something woke me up!");
     
     if (options != null) {
         
         NSObject launchedFromLocation;
         if (options.TryGetValue (UIApplication.LaunchOptionsLocationKey, out launchedFromLocation)) {
             
             if (((NSNumber)launchedFromLocation).BoolValue) {
                 Console.WriteLine ("Launched From Location Event");
                 
                 // wrapper method to ensure the location manager is created
                 // in the case where the app was launched in the background 
                 // due to a location update
                 LocationHelper.Initialize ();
             }
         }
     }
     
     window.AddSubview (locationTableController.View);
     
     window.MakeKeyAndVisible ();
     
     return true;
 }
Example #11
0
        private static void Load()
        {
            ExceptionUtility.Try(() =>
            {
                //	MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure = false;
                if (!File.Exists("info.plist"))
                {
                    return;
                }

                var appSettingsNsDictionary = new NSDictionary("info.plist");
                var keys = appSettingsNsDictionary.Keys;
                AppSettingsDictionary.Clear();
                foreach (var keyNsObject in keys)
                {
                    var key = keyNsObject.ToString();
                    NSObject valueNsObject;
                    var found = appSettingsNsDictionary.TryGetValue(keyNsObject, out valueNsObject);
                    if (!found)
                    {
                        continue;
                    }
                    var stringValue            = valueNsObject.ToString();
                    AppSettingsDictionary[key] = stringValue;
                }
            });
        }
Example #12
0
        private bool IsUniversalLinks(NSDictionary launchOptions)
        {
            if (launchOptions == null)
            {
                _loggerService.Value.Info("Not from universal links.");
                return(false);
            }

            if (!launchOptions.TryGetValue(UIApplication.LaunchOptionsUserActivityDictionaryKey, out NSObject result))
            {
                _loggerService.Value.Info("Not from universal links.");
                return(false);
            }

            if (result == null)
            {
                _loggerService.Value.Info("Not from universal links.");
                return(false);
            }

            _loggerService.Value.Debug($"LaunchOptionsUserActivityDictionaryKey result={result}");
            _loggerService.Value.Info("From universal links.");

            return(true);
        }
Example #13
0
        private bool IsLocalNotification(NSDictionary launchOptions)
        {
            if (launchOptions == null)
            {
                _loggerService.Value.Info("Not from local notification.");
                return(false);
            }

            if (!launchOptions.TryGetValue(UIApplication.LaunchOptionsLocalNotificationKey, out NSObject result))
            {
                _loggerService.Value.Info("Not from local notification.");
                return(false);
            }

            if (result == null)
            {
                _loggerService.Value.Info("Not from local notification.");
                return(false);
            }

            _loggerService.Value.Debug($"LaunchOptionsLocalNotificationKey result={result}");
            _loggerService.Value.Info("From local notification.");

            return(true);
        }
Example #14
0
        public override bool WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
        {
            /*
             * UILocalNotification tn = new UILocalNotification();
             * tn.AlertBody = "WillFinishLaunching";
             * UIApplication.SharedApplication.PresentLocationNotificationNow(tn);
             */

            if (launchOptions != null)
            {
                NSObject launchFromLocations;
                if (launchOptions.TryGetValue(UIApplication.LaunchOptionsLocationKey, out launchFromLocations))
                {
                    if (((NSNumber)launchFromLocations).BoolValue)
                    {
                        UILocalNotification ln = new UILocalNotification();
                        ln.AlertBody   = "position changed!";
                        ln.AlertAction = "просмотреть";
                        UIApplication.SharedApplication.PresentLocationNotificationNow(ln);
                    }
                }
            }

            return(true);
        }
Example #15
0
        public static bool PathIsNetworkPath(string path)
        {
            var     url   = NSUrl.FromFilename(path);
            var     keys  = new NSString[] { new NSString(NSURLVolumeIsLocalKey) };
            NSError error = null;

            NSDictionary d = url.GetResourceValues(keys, out error);

            if (error != null || d == null)
            {
                throw new ApplicationException("Can't determine if the path is a network path");
            }

            NSObject o;

            if (d.TryGetValue(new NSString(NSURLVolumeIsLocalKey), out o))
            {
                if (o is NSNumber)
                {
                    return(!((NSNumber)(o)).BoolValue);
                }
            }

            return(false);
        }
        public void DidReceiveUserInfo(WCSession session, NSDictionary <NSString, NSObject> userInfo)
        {
            var writer = new BarcodeWriter <UIImage>
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions
                {
                    Height = 200,
                    Width  = 200,
                    Margin = 0
                },
                Renderer = new BarcodeRenderer()
            };

            var qrCodeUrl = new NSObject();

            userInfo.TryGetValue(new NSString("qrCode"), out qrCodeUrl);

            var img = writer.Write(qrCodeUrl.ToString());

            myImage.SetImage(img);
            myImage.SetRelativeWidth(0.98f, 0);
            myImage.SetRelativeHeight(0.98f, 0);

            var asdf = WKExtension.SharedExtension.Delegate as ExtensionDelegate;

            HealthStore.EndWorkoutSession(asdf.WorkoutSession);
        }
Example #17
0
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler)
        {
            //NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

            // The aps is a dictionary with the template values in it
            // You can adjust this section to do whatever you need to with the push notification

            //string alert = string.Empty;
            //if (aps.ContainsKey(new NSString("alert")))
            //	alert = (aps[new NSString("alert")] as NSString).ToString();

            //string badge = string.Empty;
            //if (aps.ContainsKey(new NSString("badge")))
            //	badge = (aps[new NSString("badge")] as NSNumber).ToString();

            //string payload = string.Empty;
            //if (aps.ContainsKey(new NSString("payload")))
            //	payload = (aps[new NSString("payload")] as NSString).ToString();

            //var payloadData = JsonConvert.DeserializeObject<NotificationPayload>(payload);

            if (!userInfo.TryGetValue(new NSString("aps"), out NSObject aps))
            {
                return;
            }

            var apsHash   = aps as NSDictionary;
            var alertHash = apsHash.ObjectForKey(new NSString("alert")) as NSDictionary;

            var badgeValue = alertHash.ObjectForKey(new NSString("badge"));

            if (badgeValue != null)
            {
                if (int.TryParse(new NSString(badgeValue.ToString()), out int count))
                {
                    UIApplication.SharedApplication.ApplicationIconBadgeNumber = count;
                }
            }

            var notification = new NotificationEventArgs();

            if (alertHash.TryGetValue(new NSString("payload"), out NSObject payloadValue))
            {
                notification.Payload = JsonConvert.DeserializeObject <Dictionary <string, string> >(payloadValue.ToString());
            }

            if (alertHash.TryGetValue(new NSString("title"), out NSObject titleValue))
            {
                notification.Title = titleValue.ToString();
            }

            if (alertHash.TryGetValue(new NSString("body"), out NSObject messageValue))
            {
                notification.Message = messageValue.ToString();
            }

            ((PushNotificationHandler)Push.Instance).NotifyReceived(notification);
        }
Example #18
0
 bool TryGetValue(NSDictionary source, NSObject key, out NSObject result)
 {
     result = null;
     if (key != null)
     {
         return(source.TryGetValue(key, out result));
     }
     return(false);
 }
Example #19
0
 bool TryGetValue(NSDictionary source, NSObject?key, [NotNullWhen(true)] out NSObject?result)
 {
     if (key != null)
     {
         return(source.TryGetValue(key, out result));
     }
     result = null;
     return(false);
 }
Example #20
0
        internal UITextAttributes(NSDictionary dict)
        {
            if (dict == null)
                return;

            NSObject val;

            if (dict.TryGetValue (UITextAttributesConstants.Font, out val))
                Font = val as UIFont;
            if (dict.TryGetValue (UITextAttributesConstants.TextColor, out val))
                TextColor = val as UIColor;
            if (dict.TryGetValue (UITextAttributesConstants.TextShadowColor, out val))
                TextShadowColor = val as UIColor;
            if (dict.TryGetValue (UITextAttributesConstants.TextShadowOffset, out val)) {
                var value = val as NSValue;
                if (value != null)
                    TextShadowOffset = value.UIOffsetValue;
            }
        }
Example #21
0
 /// <summary>
 /// Entry point if the app was not running
 /// </summary>
 private void HandleNotifications(NSDictionary options)
 {
     if (options != null)
     {
         if (options.TryGetValue(FromObject(UIApplication.LaunchOptionsUrlKey), out var value))
         {
             OpenDeepLink((NSUrl)value);
         }
     }
 }
Example #22
0
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            NSObject inAppMessage;

            var success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                var alert = new UIAlertView("Notification!", inAppMessage.ToString(), null, "OK", null);
                alert.Show();
            }
        }
        public void ReceivedRemoteNotification(NSDictionary userInfo)
        {
            NSObject inAppMessage;

            bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                if (this.NotificationRecieved != null)
                this.NotificationRecieved(this, new AzureNotificationEventArgs(inAppMessage.ToString()));
            }
        }
Example #24
0
        private bool TryGetUserActivityFromLaunchOptions(NSDictionary launchOptions, out NSUserActivity userActivity)
        {
            userActivity = null;

            if (launchOptions.TryGetValue(UIApplication.LaunchOptionsUserActivityDictionaryKey, out var userActivityObject) &&
                userActivityObject is NSDictionary userActivityDictionary)
            {
                userActivity = userActivityDictionary.Values.OfType <NSUserActivity>().FirstOrDefault();
            }

            return(userActivity != null);
        }
Example #25
0
        static bool TryGet <T>(this NSDictionary dic, string key, out T value)
            where T : NSObject
        {
            if (dic != null && dic.TryGetValue((NSString)key, out var obj) && obj is T val)
            {
                value = val;
                return(true);
            }

            value = default(T);
            return(false);
        }
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            NSObject inAppMessage;

            bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                var alert = new UIAlertView("Got push notification", inAppMessage.ToString(), null, "OK", null);
                alert.Show();
            }
        }
Example #27
0
        bool TryGetValue(NSDictionary source, NSObject key, out NSObject result)
        {
            var b = false;

            result = null;
            if (key != null)
            {
                source.TryGetValue(key, out result);
                b = true;
            }
            return(b);
        }
Example #28
0
        public async Task DidReceiveRemoteNotificationAsync(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler)
        {
            backgroundFetchHandler = completionHandler;

            try {
                var syncManager = ServiceContainer.Resolve <ISyncManager> ();

                NSObject entryIdObj, modifiedAtObj;
                userInfo.TryGetValue(updatedAtConst, out modifiedAtObj);
                userInfo.TryGetValue(taskIdConst, out entryIdObj);

                var entryId = Convert.ToInt64(entryIdObj.ToString());

                var dataStore = ServiceContainer.Resolve <IDataStore> ();
                var rows      = await dataStore.Table <TimeEntryData> ()
                                .Where(r => r.RemoteId == entryId)
                                .ToListAsync();

                var entry = rows.FirstOrDefault();

                var modifiedAt = ParseDate(modifiedAtObj.ToString());

                var localDataNewer = entry != null && modifiedAt <= entry.ModifiedAt.ToUtc();
                var skipSync       = lastSyncTime.HasValue && modifiedAt < lastSyncTime.Value;

                if (syncManager.IsRunning || localDataNewer || skipSync)
                {
                    return;
                }

                syncManager.Run(SyncMode.Pull);
                if (syncManager.IsRunning)
                {
                    lastSyncTime = Time.UtcNow;
                }
            } catch (Exception ex) {
                var log = ServiceContainer.Resolve <ILogger> ();
                log.Error(Tag, ex, "Failed to process pushed message.");
            }
        }
Example #29
0
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            Console.WriteLine(userInfo.ToString());
            NSObject inAppMessage;

            bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                var alert = new UIAlertView("Got push notification", inAppMessage.ToString(), null, "OK", null);
                alert.Show();
            }
        }
        // The return result from this method is combined with the return result from the
        // application:willFinishLaunchingWithOptions: method to determine if a URL should be handled.
        // If either method returns false, the URL is not handled.
        public override bool WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
        {
            NSObject url;

            if (launchOptions != null && !launchOptions.TryGetValue(new NSString("UIApplicationLaunchOptionsURLKey"), out url))
            {
                // if the key is not in the dictionary
                System.Diagnostics.Debug.WriteLine("WillFinishLaunching with launchOptions: {0}", url.ToString());
                return(true);
            }

            return(false);
        }
 private void FindLink(NSDictionary dic, NSRange range, ref bool stop)
 {
     if (dic.ContainsKey(new NSString("NSLink")))
     {
         NSObject val;
         dic.TryGetValue(new NSString("NSColor"), out val);
         UIColor color = val as UIColor;
         if (color != null)
         {
             (Target as UITextView).TintColor = color;
         }
     }
 }
        public void TryGetValueTest()
        {
            var value1 = NSDate.FromTimeIntervalSinceNow(1);
            var value2 = NSDate.FromTimeIntervalSinceNow(2);
            var value3 = NSDate.FromTimeIntervalSinceNow(3);
            var key1   = new NSString("key1");
            var key2   = new NSString("key2");
            var key3   = new NSString("key3");

            var dict = new NSDictionary <NSString, NSDate> (
                new NSString [] { key1, key2 },
                new NSDate[] { value1, value1 }
                );

            NSDate value;

            Assert.True(dict.TryGetValue(key1, out value), "a");
            Assert.AreSame(value1, value, "a same");

            Assert.False(dict.TryGetValue(key3, out value), "b");
            Assert.IsNull(value, "b null");
        }
Example #33
0
        public async Task InitializeAsync(UIApplicationDelegate appDelegate, NSDictionary options)
        {
            using (var _ = _analyticsService.StartTrace(this, "iOs Push Notifications Initialization"))
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                                                                          (granted, error) =>
                    {
                        if (granted)
                        {
                            _analyticsService.TraceInformation(this, "Permission granted for push notifications");
                            appDelegate.InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                        }
                        else
                        {
                            if (error?.Code != null)
                            {
                                _analyticsService.TraceError(this, "Failed to get permission for push notifications", "ErrorCode", error.Code.ToString());
                            }
                            else
                            {
                                _analyticsService.TraceWarning(this, "Permission for push notifications not granted");
                            }
                        }
                    });
                }
                else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet());

                    UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                }
                else
                {
                    const UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                    UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                }

                if (options != null)
                {
                    if (options.TryGetValue(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey"), out var tapped))
                    {
                        _analyticsService.TraceVerbose(this, "Notification payload available for new app session");
                        await HandleMessageReceivedAsync(UIApplicationState.Inactive, (NSDictionary)tapped);
                    }
                }
            }
        }
Example #34
0
        /// <summary>
        /// Handles the FinishedLaunching event of the application delegate.
        /// </summary>
        /// <param name="app">The current application.</param>
        /// <param name="options">The application options.</param>
        /// <returns><c>true</c> - if the application was launched; <c>false</c> otherwise.</returns>
        /// <remarks>
        ///   <para>
        ///     This method is invoked when the application has loaded and is ready to run. In this
        ///     method you should instantiate the window, load the UI into it and then make the window
        ///     visible.
        ///   </para>
        ///   <para>
        ///     You have 17 seconds to return from this method, or iOS will terminate your application.
        ///   </para>
        /// </remarks>
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // Initialize the platform dependent components
            Xamarin.Forms.Forms.Init();
            Xamarin.FormsMaps.Init();
            MediaPicker.Instance = new Media.MediaPickerIOS();
            Settings.Instance    = new SettingsIOS();

            // Setup exception handler
            AppDomain.CurrentDomain.UnhandledException += AppDelegate.CurrentDomainOnUnhandledException;
            AppDelegate.DisplayCrashReport();

            // Get the device identifier
#if !TARGET_IPHONE_SIMULATOR
            var deviceUuid = UIDevice.CurrentDevice.IdentifierForVendor;
#else
            var deviceUuid = new NSUuid("CA90424A-5E89-468E-BC7B-9DE7D82FC02D");
#endif

            // Initialize the application
            // ReSharper disable once UseObjectOrCollectionInitializer
            var application = new App();
            application.CurrentCultureInfo = AppDelegate.GetCurrentCultureInfo();
            application.DeviceId           = $"{Xamarin.Forms.Device.OS}:{deviceUuid.AsString()}";
            application.LaunchUriDelegate  = AppDelegate.LaunchUri;

            // If launched with the URI
            if (options != null)
            {
                NSObject obj;
                options.TryGetValue(UIApplication.LaunchOptionsUrlKey, out obj);
                var uri = obj as NSUrl;
                if (uri != null)
                {
                    // Save the URI
                    this.launchedUri = new Uri(uri.ToString());
                }
            }

            // Request notification permission
            var pushSettings =
                UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());
            UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);

            // Load the current application
            this.LoadApplication(application);
            return(base.FinishedLaunching(app, options));
        }
Example #35
0
        public void ReceivedRemoteNotification(NSDictionary userInfo)
        {
            NSObject inAppMessage;

            bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                if (this.NotificationRecieved != null)
                {
                    this.NotificationRecieved(this, new AzureNotificationEventArgs(inAppMessage.ToString()));
                }
            }
        }
 private void ResetAlignment(NSDictionary dic, NSRange range, ref bool stop)
 {
     if (dic.ContainsKey(new NSString("NSParagraphStyle")))
     {
         //set the alignment to the alignment of the label
         NSObject val;
         dic.TryGetValue(new NSString("NSParagraphStyle"), out val);
         NSParagraphStyle style = val as NSParagraphStyle;
         if (style != null)
         {
             style.Alignment = (this.Target as UILabel).TextAlignment;
         }
     }
 }
Example #37
0
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            // NOTE: Don't call the base implementation on a Model class
            // see http://docs.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events 

            Debug.WriteLine(userInfo.ToString());
            NSObject inAppMessage;

            bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

            if (success)
            {
                var alert = new UIAlertView("Got push notification", inAppMessage.ToString(), null, "OK", null);
                alert.Show();
            }
        }
Example #38
0
		void ProcessPendingPayload(NSDictionary userInfo)
		{
			if(userInfo == null)
				return;

			NSObject aps, payload, innerPayload;
			if(userInfo.TryGetValue(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey"), out payload))
			{
				if(((NSDictionary)payload).TryGetValue(new NSString("aps"), out aps))
				{
					if(((NSDictionary)aps).TryGetValue(new NSString("payload"), out innerPayload))
					{
						var notificationPayload = JsonConvert.DeserializeObject<NotificationPayload>(innerPayload.ToString());
						App.Current.OnIncomingPayload(notificationPayload);
					}
				}
			}
		}
Example #39
0
		public async override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
		{
			NSObject inAppMessage;

			bool success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);

			if (success)
			{
				string[] parsedMessage = inAppMessage.ToString ().Split (',');

				//used for updating chats
				if(parsedMessage[0].Equals("comment")){
					await APushes.CommentPush(parsedMessage);
				}
				else if (parsedMessage[0].Equals("like"))
				{
					await APushes.LikePush(parsedMessage);
				}
				//standard use for notifications
				else if(parsedMessage[0].Equals("medal")){
					APushes.MedalPush(parsedMessage);
				}
				else if (parsedMessage[0].Equals("droplet"))
				{
					await APushes.DropletPush(parsedMessage);
				}
				else if (parsedMessage[0].Equals("dbNotification"))
				{
					APushes.DBNotificationPush(parsedMessage);
				}
				else if (parsedMessage[0].Equals("clubRequest"))
				{
					await APushes.ClubRequestPush(parsedMessage);
				}

			}
		}
Example #40
0
        public async Task DidReceiveRemoteNotificationAsync (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            backgroundFetchHandler = completionHandler;

            try {
                var syncManager = ServiceContainer.Resolve<ISyncManager> ();

                NSObject entryIdObj, modifiedAtObj;
                userInfo.TryGetValue (updatedAtConst, out modifiedAtObj);
                userInfo.TryGetValue (taskIdConst, out entryIdObj);

                var entryId = Convert.ToInt64 (entryIdObj.ToString ());

                var dataStore = ServiceContainer.Resolve<IDataStore> ();
                var rows = await dataStore.Table<TimeEntryData> ()
                           .Where (r => r.RemoteId == entryId)
                           .ToListAsync ();
                var entry = rows.FirstOrDefault();

                var modifiedAt = ParseDate (modifiedAtObj.ToString());

                var localDataNewer = entry != null && modifiedAt <= entry.ModifiedAt.ToUtc ();
                var skipSync = lastSyncTime.HasValue && modifiedAt < lastSyncTime.Value;

                if (syncManager.IsRunning || localDataNewer || skipSync) {
                    return;
                }

                syncManager.Run (SyncMode.Pull);
                if (syncManager.IsRunning) {
                    lastSyncTime = Time.UtcNow;
                }
            } catch (Exception ex) {
                var log = ServiceContainer.Resolve<ILogger> ();
                log.Error (Tag, ex, "Failed to process pushed message.");
            }
        }
Example #41
0
        internal MPNowPlayingInfo(NSDictionary source)
        {
            if (source == null)
                return;

            NSObject result;

            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyElapsedPlaybackTime, out result))
                ElapsedPlaybackTime = (result as NSNumber).DoubleValue;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyPlaybackRate, out result))
                PlaybackRate = (result as NSNumber).DoubleValue;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyPlaybackQueueIndex, out result))
                PlaybackQueueIndex = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyPlaybackQueueCount, out result))
                PlaybackQueueCount = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyChapterNumber, out result))
                ChapterNumber = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyChapterCount, out result))
                ChapterCount = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPNowPlayingInfoCenter.PropertyDefaultPlaybackRate, out result))
                DefaultPlaybackRate = (double) (result as NSNumber).DoubleValue;
            if (source.TryGetValue (MPMediaItem.AlbumTrackCountProperty, out result))
                AlbumTrackCount = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPMediaItem.AlbumTrackNumberProperty, out result))
                AlbumTrackNumber = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPMediaItem.DiscCountProperty, out result))
                DiscCount = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPMediaItem.DiscNumberProperty, out result))
                DiscNumber = (int) (result as NSNumber).UInt32Value;
            if (source.TryGetValue (MPMediaItem.PersistentIDProperty, out result))
                PersistentID = (result as NSNumber).UInt64Value;
            if (source.TryGetValue (MPMediaItem.PlaybackDurationProperty, out result))
                PlaybackDuration = (result as NSNumber).DoubleValue;

            if (source.TryGetValue (MPMediaItem.AlbumTitleProperty, out result))
                AlbumTitle = (string) (result as NSString);
            if (source.TryGetValue (MPMediaItem.ArtistProperty, out result))
                Artist = (string) (result as NSString);
            if (source.TryGetValue (MPMediaItem.ArtworkProperty, out result))
                Artwork = result as MPMediaItemArtwork;
            if (source.TryGetValue (MPMediaItem.ComposerProperty, out result))
                Composer = (string) (result as NSString);
            if (source.TryGetValue (MPMediaItem.GenreProperty, out result))
                Genre = (string) (result as NSString);
            if (source.TryGetValue (MPMediaItem.TitleProperty, out result))
                Title = (string) (result as NSString);
        }
Example #42
0
        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            SensusServiceHelper.Initialize(() => new iOSSensusServiceHelper());

            // facebook settings
            Settings.AppID = "873948892650954";
            Settings.DisplayName = "Sensus";

            Forms.Init();
            FormsMaps.Init();
            MapExtendRenderer.Init();

            ToastNotificatorImplementation.Init();

            App app = new App();
            LoadApplication(app);

            uiApplication.RegisterUserNotificationSettings(UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert, new NSSet()));

            _serviceHelper = SensusServiceHelper.Get() as iOSSensusServiceHelper;

            UiBoundSensusServiceHelper.Set(_serviceHelper);
            app.SensusMainPage.DisplayServiceHelper(UiBoundSensusServiceHelper.Get(true));

            if (launchOptions != null)
            {
                NSObject launchOptionValue;
                if (launchOptions.TryGetValue(UIApplication.LaunchOptionsLocalNotificationKey, out launchOptionValue))
                    ServiceNotificationAsync(launchOptionValue as UILocalNotification);
                else if (launchOptions.TryGetValue(UIApplication.LaunchOptionsUrlKey, out launchOptionValue))
                    Protocol.DisplayFromBytesAsync(File.ReadAllBytes((launchOptionValue as NSUrl).Path));
            }

            // service all other notifications whose fire time has passed
            foreach (UILocalNotification notification in uiApplication.ScheduledLocalNotifications)
                if (notification.FireDate.ToDateTime() <= DateTime.UtcNow)
                    ServiceNotificationAsync(notification);

            return base.FinishedLaunching(uiApplication, launchOptions);
        }
Example #43
0
		public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
		{
			ProcessNotification(userInfo, notiCheck);



			NSObject Type;
			NSObject Id;

			var success = userInfo.TryGetValue(new NSString("type"), out Type);
			if (success)
			{
				success = userInfo.TryGetValue(new NSString("id"), out Id);
				NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
				string alert = string.Empty;
				if (aps.ContainsKey(new NSString("alert"))) 
					alert = (aps[new NSString("alert")] as NSString).ToString();
				if (success)
				{
					App.notificationController.HandlePushNotification(Type.ToString(), Id.ToString(), notiCheck, alert);
				}
			}
		}