public void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            if (indexPath.Section == 0 && indexPath.Row == 0)
            {
                //Xamarin    
                OpenUrl("http://www.xamarin.com/");
            }


			if (indexPath.Section == 0 && indexPath.Row == 1)
			{
				var sfViewController = new SFSafariViewController(new NSUrl("ReleaseNotes.md"), true);
				PresentViewControllerAsync(sfViewController, true);
			}

            if (indexPath.Section == 1 && indexPath.Row == 0)
            {
                //Facebook
                OpenUrl("https://www.facebook.com/beerdrinkinapp");
            }

            if (indexPath.Section == 1 && indexPath.Row == 1)
            {
                //Twitter
                OpenUrl("http://twitter.com/BeerDrinkinApp");
            }
        }
 void OpenUrl(string url)
 {
     var sfViewController = new SFSafariViewController(new NSUrl(url), true);
     sfViewController.View.TintColor = Helpers.Style.Colors.NavigationBar;
     sfViewController.View.BackgroundColor = Helpers.Style.Colors.NavigationBar;  
     PresentViewControllerAsync(sfViewController, true);
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            openButton.TouchUpInside += (sender, e) => {
                var sfvc = new SFSafariViewController (new NSUrl("http://xamarin.com"),true);
                PresentViewController(sfvc, true, null);
            };
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Show an action sheet with Schedule, Calendar & more when navbar button is clicked.
			this.NavigationItem.RightBarButtonItem.Clicked += (sender, e) => {
				UIActionSheet a = new UIActionSheet("Options");
				nint s = a.AddButton("Schedule"), co = a.AddButton("Call-Out"),c = a.AddButton("Calendar"), b = a.AddButton("Change Filters");
				a.AddButton("Cancel");

				a.Clicked += (sr, ev) => {
					if (ev.ButtonIndex == s) {
						if (UIDevice.CurrentDevice.CheckSystemVersion(9,0)) {
							var sfViewCtrl = new SFSafariViewController (new NSUrl(Api.SCHEDULE_URL));
							PresentViewControllerAsync (sfViewCtrl, true);
						} else {
							UIApplication.SharedApplication.OpenUrl(new NSUrl(Api.SCHEDULE_URL));
						}
					} else if (ev.ButtonIndex == c) {
						this.PerformSegue("Calendar", this);
					} else if (ev.ButtonIndex == co) {
						this.NavigationController.PushViewController(new CalloutViewCtrl(), true);
					} else if (ev.ButtonIndex == b) {
						UIActionSheet aSheet = new UIActionSheet("Options");
						nint all = aSheet.AddButton("Show All"), hide = aSheet.AddButton("Hide Biz Calc"), only = aSheet.AddButton("Biz Calc Only");
						aSheet.Clicked += (sdr, evt) => {
							if (evt.ButtonIndex == all) {
								KeyStore.HideBizCalc = KeyStore.BizCalcOnly = false;
							} else if (evt.ButtonIndex == hide) {
								KeyStore.HideBizCalc = true;
								KeyStore.BizCalcOnly = false;
							} else if (evt.ButtonIndex == only) {
								KeyStore.HideBizCalc = false;
								KeyStore.BizCalcOnly = true;
							}
							this.UpdateData();
						};
						aSheet.ShowInView(this.View);
					}
				};

				a.ShowInView(this.View);
			};

			// Refresh Data if the RefreshControl is manually pulled down.
			this.RefreshControl.ValueChanged += (sender, e) => {
				this.UpdateData();
			};

			this.UpdateData ();
		}
        private Task <bool> ShowSafariViewController(Uri uri)
        {
            var safari = new SFSafariViewController(uri);
            // Probably a bad idea
            var root = UIApplication.SharedApplication
                       .KeyWindow
                       .RootViewController;

            if (root.PresentedViewController == null)
            {
                root.PresentViewController(safari, true, null);
            }
            else
            {
                root.PresentedViewController.PresentViewController(safari, true, null);
            }

            return(Task.FromResult(true));
        }
 public static bool ResumeAuth(string url)
 {
     try {
         var uri      = new Uri(url);
         var redirect = uri.Scheme;
         var auth     = authenticators [redirect];
         var s        = auth.CheckUrl(uri, new System.Net.Cookie [0]);
         if (s)
         {
             authenticators.Remove(redirect);
             CurrentController?.DismissViewControllerAsync(true);
             CurrentController = null;
         }
         return(s);
     } catch (Exception ex) {
         Console.WriteLine(ex);
     }
     return(false);
 }
Beispiel #7
0
        static async Task <bool> PlatformOpenAsync(Uri uri, BrowserLaunchOptions options)
        {
            var nativeUrl = new NSUrl(uri.AbsoluteUri);

            switch (options.LaunchMode)
            {
            case BrowserLaunchMode.SystemPreferred:
                var sfViewController = new SFSafariViewController(nativeUrl, false);
                var vc = Platform.GetCurrentViewController();

                if (options.PreferredToolbarColor.HasValue)
                {
                    sfViewController.PreferredBarTintColor = options.PreferredToolbarColor.Value.ToPlatformColor();
                }

                if (options.PreferredControlColor.HasValue)
                {
                    sfViewController.PreferredControlTintColor = options.PreferredControlColor.Value.ToPlatformColor();
                }

                if (sfViewController.PopoverPresentationController != null)
                {
                    sfViewController.PopoverPresentationController.SourceView = vc.View;
                }
                await vc.PresentViewControllerAsync(sfViewController, true);

                break;

            case BrowserLaunchMode.External:
                if (Platform.HasOSVersion(12, 0))
                {
                    return(await UIApplication.SharedApplication.OpenUrlAsync(nativeUrl, new UIApplicationOpenUrlOptions()));
                }
                else
                {
                    UIApplication.SharedApplication.OpenUrl(nativeUrl);
                }
                break;
            }

            return(true);
        }
        public void NavigateToBankIdWebView()
        {
            //if (loginStoryboard != null)
            //        {
            //var webview = loginStoryboard.InstantiateViewController("BankIdWebView") as BankIdWebView;
            //if (webview != null)
            //           {
            //               webview.Presenter = presenter;
            //NavigationBar.Hidden = false;
            //PushViewController(webview, true);
            //    }
            //}

            (UIApplication.SharedApplication.Delegate as AppDelegate).LoginPresenter = presenter;

            var url    = new NSUrl(presenter.GetAuthURL());
            var safari = new SFSafariViewController(url, true);

            PresentViewController(safari, true, null);
        }
Beispiel #9
0
        public async Task OpenBrowser(string url)
        {
            var safariViewController = new SFSafariViewController(new NSUrl(url), true)
            {
                PreferredBarTintColor     = ColorConstants.BrowserNavigationBarBackgroundColor.ToUIColor(),
                PreferredControlTintColor = ColorConstants.BrowserNavigationBarTextColor.ToUIColor()
            };

            var visibleViewController = await HelperMethods.GetVisibleViewController().ConfigureAwait(false);

            var taskCompletionSource = new TaskCompletionSource <bool>();

            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                visibleViewController.PresentViewControllerAsync(safariViewController, true);
                taskCompletionSource.SetResult(true);
            });

            await taskCompletionSource.Task.ConfigureAwait(false);
        }
Beispiel #10
0
        public override bool FinishLogin(Uri redirectUri)
        {
            var processed = base.FinishLogin(redirectUri);

            if (processed)
            {
                if (_controller != null)
                {
                    var controller = _controller;
                    var display    = _controller.PresentingViewController;
                    _controller = null;
                    controller.DismissViewController(true, () =>
                    {
                        ResetStatusBarStyle();
                        controller.Dispose();
                    });
                }
            }
            return(processed);
        }
Beispiel #11
0
        Task <BrowserResult> INativeBrowser.LaunchBrowserAsync(string url)
        {
            var tcs = new TaskCompletionSource <BrowserResult>();

            AppDelegate.CallbackHandler = async(response) =>
            {
                await safari.DismissViewControllerAsync(true);

                tcs.SetResult(new BrowserResult
                {
                    Response   = response,
                    ResultType = BrowserResultType.Success
                });
            };

            rootViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            safari             = new SFSafariViewController(new NSUrl(url));
            rootViewController.PresentViewController(safari, true, null);

            return(tcs.Task);
        }
Beispiel #12
0
        partial void Google_TouchUpInside(UIButton sender)
        {
            GUIDStorage guid = new GUIDStorage();
            Guid        obj  = Guid.NewGuid();

            guid.GUIDTOKEN = Convert.ToString(obj);

            var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
            // appDelegate.FinishedLaunching();
            Dictionary <string, string> webview = new Dictionary <string, string>();

            webview.Add("appname", this.appName);
            webview.Add("callbackguid", guid.GUIDTOKEN);
            webview.Add("apikey", this.apiKey);
            webview.Add("provider", "google");
            WebViewUrl web  = new WebViewUrl();
            var        sfvc = new SFSafariViewController(new NSUrl(web.getWebUrlWithNoCallBack(webview)), true);

            PresentViewController(sfvc, true, null);
            GetEmailPromptAutoLoginPing(this.apiKey, guid.GUIDTOKEN);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            webviewButton.TouchUpInside += (sender, e) => {
                webView = new WKWebView(View.Frame, new WKWebViewConfiguration());
                View.AddSubview(webView);

                var request = new NSUrlRequest(url);
                webView.LoadRequest(request);
            };

            safariButton.TouchUpInside += (sender, e) => {
                var sfViewController = new SFSafariViewController(url);

                PresentViewController(sfViewController, true, null);
            };

            openSafari.TouchUpInside += (sender, e) => {
                UIApplication.SharedApplication.OpenUrl(url);
            };
        }
Beispiel #14
0
        static async Task BeginAuthentication(UIViewController presentingController, WebAuthenticator authenticator)
        {
            try {
                var    uri         = (await authenticator.GetInitialUrl());
                string redirectUrl = uri.GetParameter("redirect_uri");
                var    scheme      = new Uri(redirectUrl).Scheme;
                if (!VerifyHasUrlScheme(scheme))
                {
                    authenticator.OnError($"Unable to redirect {redirectUrl}, Please add the Url Scheme to the info.plist");
                    return;
                }
                var url = new NSUrl(uri.AbsoluteUri);
                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    var controller = new SFSafariViewController(url, false)
                    {
                        Delegate = new NativeSFSafariViewControllerDelegate(authenticator),
                    };
                    authenticators [scheme] = authenticator;
                    CurrentController       = controller;
                    await presentingController.PresentViewControllerAsync(controller, true);

                    return;
                }

                var opened = UIApplication.SharedApplication.OpenUrl(url);
                if (!opened)
                {
                    authenticator.OnError("Error opening Safari");
                }
                else
                {
                    authenticators [scheme] = authenticator;
                }
            } catch (Exception ex) {
                authenticator.OnError(ex.Message);
            }
        }
Beispiel #15
0
        internal static Task <BrowserResult> Start(BrowserOptions options)
        {
            var tcs = new TaskCompletionSource <BrowserResult>();

            // Create Safari controller
            var safari = new SFSafariViewController(new NSUrl(options.StartUrl))
            {
                Delegate = new SafariViewControllerDelegate(),
                ModalPresentationStyle = UIModalPresentationStyle.FormSheet,
                DismissButtonStyle     = SFSafariViewControllerDismissButtonStyle.Cancel
            };

            async void Callback(string response)
            {
                ActivityMediator.Instance.ActivityMessageReceived -= Callback;

                if (response == "UserCancel")
                {
                    BrowserMediator.Instance.Cancel();
                    tcs.SetResult(Canceled());
                }
                else
                {
                    BrowserMediator.Instance.Success();
                    await safari.DismissViewControllerAsync(true); // Close Safari

                    safari.Dispose();
                    tcs.SetResult(Success(response));
                }
            }

            ActivityMediator.Instance.ActivityMessageReceived += Callback;

            // Launch Safari
            FindRootController().PresentViewController(safari, true, null);

            return(tcs.Task);
        }
Beispiel #16
0
        partial void Facebook_TouchUpInside(UIButton sender)
        {
            // GetEmailPromptAutoLoginPing(apikey, guid.GUIDTOKEN);
            GUIDStorage guid = new GUIDStorage();
            Guid        obj  = Guid.NewGuid();

            guid.GUIDTOKEN = Convert.ToString(obj);

            var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
            // appDelegate.FinishedLaunching();
            Dictionary <string, string> webview = new Dictionary <string, string>();

            webview.Add("appname", this.appName);
            webview.Add("callbackguid", guid.GUIDTOKEN);
            webview.Add("apikey", this.apiKey);
            webview.Add("provider", "facebook");
            WebViewUrl web  = new WebViewUrl();
            var        sfvc = new SFSafariViewController(new NSUrl(web.getWebUrlWithNoCallBack(webview)), true);

            PresentViewController(sfvc, true, null);
            // for this api call for no callback function if you need to social login the you need to add a nocallback feture form loginradius backend.
            GetEmailPromptAutoLoginPing(this.apiKey, guid.GUIDTOKEN);
        }
Beispiel #17
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            Title = EventObj.DisplayEventName;
            descriptionLabel.Text = EventObj?.EventDescription;
            startTimeLabel.Text   = EventObj?.StartTime;
            endTimeLabel.Text     = EventObj?.EndTime;

            var startText = EventObj.StartDate.Humanize();

            if (startText.Contains("ago"))
            {
                dayLabel.TextColor = "FB537B".ToUIColor();
                dayLabel.Text      = $"Started {startText}";
            }
            else
            {
                dayLabel.Text = $"Starts {startText}";
            }

            if (!string.IsNullOrEmpty(EventObj.RegistrationLink) && EventObj.OpenRegistration == true)
            {
                registerForEventButton.Hidden         = false;
                registerForEventButton.TouchUpInside += (sender, e) =>
                {
                    var sfViewController = new SFSafariViewController(new NSUrl(EventObj.RegistrationLink));
                    PresentViewControllerAsync(sfViewController, true);
                };
            }
            else
            {
                registerForEventButton.Hidden = true;
            }

            SetupTechnologyScrollBar();
        }
Beispiel #18
0
        protected override void DisplayLoginPage(Uri uri)
        {
            Assert.State(_controller).IsNull("Login page still displaying another page");

            _controller = new SFSafariViewController(uri, false);
            var loginPageDelegate = new LoginPageDelgate(this);

            loginPageDelegate.OnFinish = ResetStatusBarStyle;
            _controller.Delegate       = loginPageDelegate;

            UIViewController root = _root;

            if (root == null)
            {
                root = UIApplication.SharedApplication.KeyWindow.RootViewController;
            }

            if (root == null)
            {
                throw new InvalidOperationException("Cannot display login page - " +
                                                    "no root view controller specified and " +
                                                    "there is no displayed window or " +
                                                    "displayed window does not have root view controller");
            }

            //Find topmost modal dialog to present login page
            while (root.PresentedViewController != null && root != root.PresentedViewController && !root.PresentedViewController.IsBeingDismissed)
            {
                root = root.PresentedViewController;
            }

            _lastStatusBarStyle = UIApplication.SharedApplication.StatusBarStyle;
            _controller.ModalPresentationStyle = UIModalPresentationStyle.Popover;
            root.PresentViewController(_controller, true, null);
            UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
        }
Beispiel #19
0
        static async Task <bool> PlatformOpenAsync(Uri uri, BrowserLaunchMode launchMode)
        {
            var nativeUrl = new NSUrl(uri.AbsoluteUri);

            switch (launchMode)
            {
            case BrowserLaunchMode.SystemPreferred:
                var sfViewController = new SFSafariViewController(nativeUrl, false);
                var vc = Platform.GetCurrentViewController();

                if (sfViewController.PopoverPresentationController != null)
                {
                    sfViewController.PopoverPresentationController.SourceView = vc.View;
                }
                await vc.PresentViewControllerAsync(sfViewController, true);

                break;

            case BrowserLaunchMode.External:
                return(await UIApplication.SharedApplication.OpenUrlAsync(nativeUrl, new UIApplicationOpenUrlOptions()));
            }

            return(true);
        }
Beispiel #20
0
        static Task PlatformOpenAsync(Uri uri, BrowserLaunchMode launchMode)
        {
            var nativeUrl = new NSUrl(uri.AbsoluteUri);

            switch (launchMode)
            {
            case BrowserLaunchMode.SystemPreferred:
                var sfViewController = new SFSafariViewController(nativeUrl, false);
                var vc = Platform.GetCurrentViewController();

                if (sfViewController.PopoverPresentationController != null)
                {
                    sfViewController.PopoverPresentationController.SourceView = vc.View;
                }
                vc.PresentViewController(sfViewController, true, null);
                break;

            case BrowserLaunchMode.External:
                UIKit.UIApplication.SharedApplication.OpenUrl(nativeUrl);
                break;
            }

            return(Task.CompletedTask);
        }
Beispiel #21
0
 public void DidFinish(SFSafariViewController controller)
 {
     DismissViewController(true, null);
 }
Beispiel #22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            bar = new UINavigationBar(new CGRect(0, 0, Width, 45));
            bar.BarTintColor = testColor;
            View.AddSubview(bar);

            barText                 = new UILabel(new RectangleF(0, 6, Width, 45));
            barText.Text            = "NewsApp";
            barText.TextAlignment   = UITextAlignment.Center;
            barText.Font            = UIFont.SystemFontOfSize(18);
            barText.TextColor       = UIColor.White;
            barText.BackgroundColor = UIColor.Clear;
            View.AddSubview(barText);

            similarArticles               = new UILabel(new RectangleF(0, Height - Height * 1 / 5, Width, Height * 2 / 15));
            similarArticles.Lines         = 0;
            similarArticles.Text          = "Similar Articles (1/" + articles.Count + ")";
            similarArticles.TextAlignment = UITextAlignment.Center;
            similarArticles.Font          = UIFont.SystemFontOfSize(14 + (int)(Width / 25));
            similarArticles.AdjustsFontForContentSizeCategory         = true;
            similarArticles.TranslatesAutoresizingMaskIntoConstraints = true;
            similarArticles.SizeToFit();
            similarArticles.Frame     = new RectangleF((float)(Width / 2 - similarArticles.Frame.Width / 2 - 6), Height - Height * 1 / 5, (float)(similarArticles.Frame.Width + 12), (float)similarArticles.Frame.Height);
            similarArticles.TextColor = testColor;
            View.AddSubview(similarArticles);

            leftButton       = UIButton.FromType(UIButtonType.System);
            leftButton.Frame = new RectangleF(0, (float)similarArticles.Frame.Top, (float)similarArticles.Frame.Left - 5, (float)similarArticles.Frame.Height);
            leftButton.SetTitle("<", UIControlState.Normal);
            leftButton.Font = UIFont.SystemFontOfSize(14 + (int)(Width / 25));
            leftButton.SetTitleColor(testColor, UIControlState.Normal);
            leftButton.SetTitleColor(UIColor.LightGray, UIControlState.Disabled);
            leftButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right;
            leftButton.Enabled             = false;
            View.AddSubview(leftButton);

            rightButton       = UIButton.FromType(UIButtonType.System);
            rightButton.Frame = new RectangleF((float)similarArticles.Frame.Right + 5, (float)similarArticles.Frame.Top, (float)(similarArticles.Frame.Left - 5), (float)similarArticles.Frame.Height);
            rightButton.SetTitle(">", UIControlState.Normal);
            rightButton.Font = UIFont.SystemFontOfSize(14 + (int)(Width / 25));
            rightButton.SetTitleColor(testColor, UIControlState.Normal);
            rightButton.SetTitleColor(UIColor.LightGray, UIControlState.Disabled);
            rightButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
            View.AddSubview(rightButton);

            link                     = UIButton.FromType(UIButtonType.System);
            link.Frame               = new RectangleF(Width / 20, (float)bar.Frame.Bottom + Height / 10, Width - Width / 10, Height * 7 / 10 - (float)bar.Frame.Bottom);
            link.Layer.ShadowColor   = UIColor.Gray.CGColor;
            link.Layer.Opacity       = 1f;
            link.Layer.ShadowRadius  = 5f;
            link.Layer.ShadowOffset  = new SizeF(3f, 3f);
            link.Layer.MasksToBounds = false;
            View.AddSubview(link);

            shade = new UIView(new RectangleF(Width / 30, (float)bar.Frame.Bottom + Height / 50, Width - Width / 15, (float)(Height * 7 / 8 - bar.Frame.Bottom - Height / 50)));
            shade.Layer.BackgroundColor = UIColor.FromRGB(240, 240, 240).CGColor;
            shade.Layer.CornerRadius    = 3;
            View.Add(shade);

            time           = new UILabel(new RectangleF((float)shade.Frame.Left + 2, (float)shade.Frame.Bottom, Width, 50));
            time.Font      = UIFont.SystemFontOfSize(6 + (int)(Width / 50));
            time.TextColor = UIColor.DarkGray;
            time.Text      = "00:00:00 till next refresh_________";
            time.TranslatesAutoresizingMaskIntoConstraints = true;
            time.SizeToFit();
            View.AddSubview(time);

            UpdateTime();
            View.SendSubviewToBack(shade);

            leftButton.TouchUpInside += (sender, e) =>
            {
                HandleSwipe(index - 1);
            };

            rightButton.TouchUpInside += (sender, e) =>
            {
                HandleSwipe(index + 1);
            };

            link.TouchDown += (sender, e) =>
            {
                shade.Layer.BackgroundColor = UIColor.FromRGB(220, 220, 220).CGColor;
            };

            link.TouchDragInside += (sender, e) =>
            {
                shade.Layer.BackgroundColor = UIColor.FromRGB(240, 240, 240).CGColor;
            };

            link.TouchUpInside += (sender, e) =>
            {
                try
                {
                    var webView = new SFSafariViewController(new NSUrl(articles[index].Url));
                    PresentViewController(webView, true, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    var alert = new UIAlertView()
                    {
                        Title   = "Cannot open link",
                        Message = "The link cannot be opened. "
                    };
                    alert.AddButton("OK");
                    alert.Show();
                }
                clicked[index] = true;
                shade.Layer.BackgroundColor = UIColor.FromRGB(240, 240, 240).CGColor;
            };

            for (int i = 0; i < articleDisplays.Length; i++)
            {
                articleDisplays[i] = InitializeArticleDisplays(articles[i]);
            }

            View.AddSubview(articleDisplays[index]);
            View.BringSubviewToFront(link);
        }
        void Link_Tapped(NSUrl obj)
        {
            var safari = new SFSafariViewController(obj);

            PresentViewController(safari, true, null);
        }
Beispiel #24
0
 public override void DidFinish(SFSafariViewController controller)
 {
     tcs.TrySetResult(null);
 }
 /// <summary>
 /// Launches a Safari view controller to the specified url
 /// </summary>
 /// <param name="url">The url to launch in a Safari view controller</param>
 private void LaunchBrowser(string url)
 {
     SafariViewController = new SFSafariViewController(Foundation.NSUrl.FromString(url));
     iOSViewController.PresentViewControllerAsync(SafariViewController, true);
 }
Beispiel #26
0
partial         void BtnSFSafariViewController_TouchUpInside(UIButton sender)
        {
            var sfViewController = new SFSafariViewController(url);
            PresentViewControllerAsync(sfViewController, true);
        }
Beispiel #27
0
        private void OpenWebPage(NSUrl url)
        {
            var safariController = new SFSafariViewController(url);

            PresentViewControllerAsync(safariController, true);
        }
Beispiel #28
0
 public override void DidCompleteInitialLoad(SFSafariViewController controller, bool didLoadSuccessfully)
 {
     return;
 }
        internal static async Task <WebAuthenticatorResult> PlatformAuthenticateAsync(Uri url, Uri callbackUrl)
        {
            // Cancel any previous task that's still pending
            if (tcsResponse?.Task != null && !tcsResponse.Task.IsCompleted)
            {
                tcsResponse.TrySetCanceled();
            }

            tcsResponse = new TaskCompletionSource <WebAuthenticatorResult>();
            redirectUri = callbackUrl;

            try
            {
                var scheme = redirectUri.Scheme;

                if (!VerifyHasUrlSchemeOrDoesntRequire(scheme))
                {
                    tcsResponse.TrySetException(new InvalidOperationException("You must register your URL Scheme handler in your app's Info.plist!"));
                    return(await tcsResponse.Task);
                }

#if __IOS__
                void AuthSessionCallback(NSUrl cbUrl, NSError error)
                {
                    if (error == null)
                    {
                        OpenUrl(cbUrl);
                    }
                    else
                    {
                        tcsResponse.TrySetException(new NSErrorException(error));
                    }
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
                {
                    was = new ASWebAuthenticationSession(new NSUrl(url.OriginalString), scheme, AuthSessionCallback);

                    if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
                    {
                        var ctx = new ContextProvider(Platform.GetCurrentWindow());
                        void_objc_msgSend_IntPtr(was.Handle, ObjCRuntime.Selector.GetHandle("setPresentationContextProvider:"), ctx.Handle);
                    }

                    using (was)
                    {
                        was.Start();
                        return(await tcsResponse.Task);
                    }
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    sf = new SFAuthenticationSession(new NSUrl(url.OriginalString), scheme, AuthSessionCallback);
                    using (sf)
                    {
                        sf.Start();
                        return(await tcsResponse.Task);
                    }
                }

                // THis is only on iOS9+ but we only support 10+ in Essentials anyway
                var controller = new SFSafariViewController(new NSUrl(url.OriginalString), false)
                {
                    Delegate = new NativeSFSafariViewControllerDelegate
                    {
                        DidFinishHandler = (svc) =>
                        {
                            // Cancel our task if it wasn't already marked as completed
                            if (!(tcsResponse?.Task?.IsCompleted ?? true))
                            {
                                tcsResponse.TrySetException(new OperationCanceledException());
                            }
                        }
                    },
                };

                currentViewController = controller;
                await Platform.GetCurrentUIViewController().PresentViewControllerAsync(controller, true);

                return(await tcsResponse.Task);
#else
                var opened = UIApplication.SharedApplication.OpenUrl(url);
                if (!opened)
                {
                    tcsResponse.TrySetException(new Exception("Error opening Safari"));
                }
#endif
            }
            catch (Exception ex)
            {
                tcsResponse.TrySetException(ex);
            }

            return(await tcsResponse.Task);
        }
 public virtual void SafariViewControllerDidFinish(SFSafariViewController controller)
 {
     GetCompletedCheckout (() => {
         if (checkout.Order != null) {
             InvokeOnMainThread (() => {
                 ShowCheckoutConfirmation ();
             });
         }
     });
 }
        private void CheckoutOnWeb(object sender, EventArgs e)
        {
            IDisposable observer = null;
            observer = NSNotificationCenter.DefaultCenter.AddObserver (AppDelegate.CheckoutCallbackNotification, notification => {
                var url = (NSUrl)notification.UserInfo ["url"];
                if (PresentedViewController is SFSafariViewController) {
                    DismissViewController (true, () => {
                        GetCompletionStatusAndCompletedCheckoutWithURL (url);
                    });
                } else {
                    GetCompletionStatusAndCompletedCheckoutWithURL (url);
                }
                observer.Dispose ();
            });

            // On iOS 9+ we should use the SafariViewController to display the checkout in-app
            if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
                var safariViewController = new SFSafariViewController (checkout.WebCheckoutURL);
                safariViewController.Delegate = this;

                PresentViewController (safariViewController, true, null);
            } else {
                UIApplication.SharedApplication.OpenUrl (checkout.WebCheckoutURL);
            }
        }
 public override void ViewDidLoad()
 {
     base.ViewDidLoad ();
     AddButton.Clicked += (sender, e) => {
         CreateTask ();
     };
     AboutButton.Clicked += (sender, e) => {
         // Safari View Controller
         var sfvc = new SFSafariViewController (new NSUrl("https://github.com/conceptdev/xamarin-ios-samples/blob/master/To9o/readme.md"),true);
         PresentViewController(sfvc, true, null);
     };
     // 3D Touch
     if (TraitCollection.ForceTouchCapability == UIForceTouchCapability.Available) {
         RegisterForPreviewingWithDelegate (this, CollectionView);
     }
 }
        public void Authenticate(Uri authorizationUri, Uri redirectUri, RequestContext requestContext)
        {
            try
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
                {
                    asWebAuthenticationSession = new AuthenticationServices.ASWebAuthenticationSession(new NSUrl(authorizationUri.AbsoluteUri),
                                                                                                       redirectUri.Scheme, (callbackUrl, error) =>
                    {
                        if (error != null)
                        {
                            ProcessCompletionHandlerError(error);
                        }
                        else
                        {
                            ContinueAuthentication(callbackUrl.ToString());
                        }
                    });

                    asWebAuthenticationSession.BeginInvokeOnMainThread(() =>
                    {
                        if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
                        {
                            // If the presentationContext is missing from the session,
                            // MSAL.NET will pick up an "authentication cancelled" error
                            // With the addition of the presentationContext, .Start() must
                            // be called on the main UI thread
                            asWebAuthenticationSession.PresentationContextProvider =
                                new ASWebAuthenticationPresentationContextProviderWindow();
                        }
                        asWebAuthenticationSession.Start();
                    });
                }

                else if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    sfAuthenticationSession = new SFAuthenticationSession(new NSUrl(authorizationUri.AbsoluteUri),
                                                                          redirectUri.Scheme, (callbackUrl, error) =>
                    {
                        if (error != null)
                        {
                            ProcessCompletionHandlerError(error);
                        }
                        else
                        {
                            ContinueAuthentication(callbackUrl.ToString());
                        }
                    });

                    sfAuthenticationSession.Start();
                }
                else
                {
                    safariViewController = new SFSafariViewController(new NSUrl(authorizationUri.AbsoluteUri), false)
                    {
                        Delegate = this
                    };
                    viewController.InvokeOnMainThread(() =>
                    {
                        viewController.PresentViewController(safariViewController, false, null);
                    });
                }
            }
            catch (Exception ex)
            {
                requestContext.Logger.ErrorPii(ex);
                throw new MsalClientException(
                          MsalError.AuthenticationUiFailedError,
                          ex.Message,
                          ex);
            }
        }
Beispiel #34
0
		// Handle force touch shortcuts being clicked.
		public bool HandleShortcutItem(UIApplicationShortcutItem shortcutItem) {
			var handled = false;

			// Anything to process?
			if (shortcutItem == null)
				return false;

			// Take action based on the shortcut type
			switch (shortcutItem.Type) {
			case "edu.usf.smartlab.000":
				if (UIDevice.CurrentDevice.CheckSystemVersion(9,0)) {
					var sfViewCtrl = new SFSafariViewController (new NSUrl(Api.SCHEDULE_URL));
					this._Controller.PresentViewControllerAsync (sfViewCtrl, true);
				} else {
					UIApplication.SharedApplication.OpenUrl(new NSUrl(Api.SCHEDULE_URL));
				}
				handled = true;
				break;
			case "edu.usf.smartlab.001":
				this._Controller.NavigationController.PushViewController(new CalloutViewCtrl(), true);
				handled = true;
				break;
			}

			// Return results
			return handled;
		}
 public void DidFinish(SFSafariViewController controller)
 {
     DismissViewController (true, null);
 }
Beispiel #36
0
        public Task <BrowserResult> InvokeAsync(BrowserOptions options)
        {
            if (string.IsNullOrWhiteSpace(options.StartUrl))
            {
                throw new ArgumentException("Missing StartUrl", nameof(options));
            }

            if (string.IsNullOrWhiteSpace(options.EndUrl))
            {
                throw new ArgumentException("Missing EndUrl", nameof(options));
            }

            // must be able to wait for the authentication session to be finished to continue
            // with setting the task result
            var tcs = new TaskCompletionSource <BrowserResult>();

            // For iOS 11, we use the new SFAuthenticationSession
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                // create the authentication session
                _authSession = new SFAuthenticationSession(
                    new NSUrl(options.StartUrl),
                    options.EndUrl,
                    (callbackUrl, error) =>
                {
                    if (error != null)
                    {
                        tcs.SetResult(new BrowserResult
                        {
                            ResultType = BrowserResultType.UserCancel,
                            Error      = error.ToString()
                        });
                    }
                    else
                    {
                        tcs.SetResult(new BrowserResult
                        {
                            ResultType = BrowserResultType.Success,
                            Response   = callbackUrl.AbsoluteString
                        });
                    }
                });

                // launch authentication session
                _authSession.Start();
            }
            else // For pre-iOS 11, we use a normal SFSafariViewController
            {
                // create Safari controller
                _safari = new SFSafariViewController(new NSUrl(options.StartUrl))
                {
                    Delegate = this
                };

                ActivityMediator.MessageReceivedEventHandler callback = null;
                callback = async(response) =>
                {
                    // remove handler
                    ActivityMediator.Instance.ActivityMessageReceived -= callback;

                    if (response == "UserCancel")
                    {
                        tcs.SetResult(new BrowserResult
                        {
                            ResultType = BrowserResultType.UserCancel
                        });
                    }
                    else
                    {
                        // Close Safari
                        await _safari.DismissViewControllerAsync(true);

                        // set result
                        tcs.SetResult(new BrowserResult
                        {
                            Response   = response,
                            ResultType = BrowserResultType.Success
                        });
                    }
                };

                // attach handler
                ActivityMediator.Instance.ActivityMessageReceived += callback;

                // https://forums.xamarin.com/discussion/24689/how-to-acces-the-current-view-uiviewcontroller-from-an-external-service
                var window = UIApplication.SharedApplication.KeyWindow;
                var vc     = window.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }

                // launch Safari
                vc.PresentViewController(_safari, true, null);
            }

            // Result for this task will be set in the authentication session
            // completion handler
            return(tcs.Task);
        }
        private void ShowCheckoutConfirmation()
        {
            var alertController = UIAlertController.Create ("Checkout complete", null, UIAlertControllerStyle.Alert);

            alertController.AddAction (UIAlertAction.Create ("Start over", UIAlertActionStyle.Default, action => {
                NavigationController.PopToRootViewController (true);
            }));
            alertController.AddAction (UIAlertAction.Create ("Show order status page", UIAlertActionStyle.Default, action => {
                var safariViewController = new SFSafariViewController (checkout.Order.StatusURL);
                safariViewController.Delegate = this;
                PresentViewController (safariViewController, true, null);
            }));

            PresentViewController (alertController, true, null);
        }
Beispiel #38
0
 public override UIActivity[] GetActivityItems(SFSafariViewController controller, NSUrl url, string title)
 {
     return(null);
 }
Beispiel #39
0
 public override void DidFinish(SFSafariViewController controller) =>
 DidFinishHandler?.Invoke(controller);
 public override void DidFinish(SFSafariViewController controller)
 {
     ActivityMediator.Instance.Send("UserCancel");
 }
Beispiel #41
0
        public async Task <WebAuthenticatorResult> AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions)
        {
            var url         = webAuthenticatorOptions?.Url;
            var callbackUrl = webAuthenticatorOptions?.CallbackUrl;
            var prefersEphemeralWebBrowserSession = webAuthenticatorOptions?.PrefersEphemeralWebBrowserSession ?? false;

            if (!VerifyHasUrlSchemeOrDoesntRequire(callbackUrl.Scheme))
            {
                throw new InvalidOperationException("You must register your URL Scheme handler in your app's Info.plist.");
            }

            // Cancel any previous task that's still pending
            if (tcsResponse?.Task != null && !tcsResponse.Task.IsCompleted)
            {
                tcsResponse.TrySetCanceled();
            }

            tcsResponse = new TaskCompletionSource <WebAuthenticatorResult>();
            redirectUri = callbackUrl;
            var scheme = redirectUri.Scheme;

#if __IOS__
            void AuthSessionCallback(NSUrl cbUrl, NSError error)
            {
                if (error == null)
                {
                    OpenUrlCallback(cbUrl);
                }
                else if (error.Domain == asWebAuthenticationSessionErrorDomain && error.Code == asWebAuthenticationSessionErrorCodeCanceledLogin)
                {
                    tcsResponse.TrySetCanceled();
                }
                else if (error.Domain == sfAuthenticationErrorDomain && error.Code == sfAuthenticationErrorCanceledLogin)
                {
                    tcsResponse.TrySetCanceled();
                }
                else
                {
                    tcsResponse.TrySetException(new NSErrorException(error));
                }

                was = null;
                sf  = null;
            }

            if (OperatingSystem.IsIOSVersionAtLeast(12, 0))
            {
                was = new ASWebAuthenticationSession(WebUtils.GetNativeUrl(url), scheme, AuthSessionCallback);

                if (OperatingSystem.IsIOSVersionAtLeast(13, 0))
                {
                    var ctx = new ContextProvider(WindowStateManager.Default.GetCurrentUIWindow());
                    was.PresentationContextProvider       = ctx;
                    was.PrefersEphemeralWebBrowserSession = prefersEphemeralWebBrowserSession;
                }
                else if (prefersEphemeralWebBrowserSession)
                {
                    ClearCookies();
                }

                using (was)
                {
                    was.Start();
                    return(await tcsResponse.Task);
                }
            }

            if (prefersEphemeralWebBrowserSession)
            {
                ClearCookies();
            }

            if (OperatingSystem.IsIOSVersionAtLeast(11, 0))
            {
                sf = new SFAuthenticationSession(WebUtils.GetNativeUrl(url), scheme, AuthSessionCallback);
                using (sf)
                {
                    sf.Start();
                    return(await tcsResponse.Task);
                }
            }

            // This is only on iOS9+ but we only support 10+ in Essentials anyway
            var controller = new SFSafariViewController(WebUtils.GetNativeUrl(url), false)
            {
                Delegate = new NativeSFSafariViewControllerDelegate
                {
                    DidFinishHandler = (svc) =>
                    {
                        // Cancel our task if it wasn't already marked as completed
                        if (!(tcsResponse?.Task?.IsCompleted ?? true))
                        {
                            tcsResponse.TrySetCanceled();
                        }
                    }
                },
            };

            currentViewController = controller;
            await WindowStateManager.Default.GetCurrentUIViewController().PresentViewControllerAsync(controller, true);
#else
            var opened = UIApplication.SharedApplication.OpenUrl(url);
            if (!opened)
            {
                tcsResponse.TrySetException(new Exception("Error opening Safari"));
            }
#endif

            return(await tcsResponse.Task);
        }