Exemplo n.º 1
0
        bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {

            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            var scheme = "app:";

            if (request.Url.Scheme != scheme.Replace(":", ""))
                return true;

            var resources = request.Url.ResourceSpecifier.Split('?');
            var method = resources[0];

            if (method == "QR")
            {
                var scanner = new ZXing.Mobile.MobileBarcodeScanner();
                scanner.Scan().ContinueWith(result => {
                    if (result != null){
                        var code = result.Result.Text;
                        this.InvokeOnMainThread(new NSAction(() => webView.LoadRequest(new NSUrlRequest(new NSUrl(MainUrl + "code?value=" + code)))));
                    }
                });
            }

            return false;
        }
Exemplo n.º 2
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            NSUrl url1 = new NSUrl(url);
            NSUrlRequest request = new NSUrlRequest(url1);
            webView.LoadRequest(request);

            this.NavigationController.NavigationBar.Hidden =  false;
            this.NavigationController.NavigationBar.TintColor = UIColor.White;
            this.NavigationController.NavigationBar.BarTintColor = UIColor.FromRGB(44/255f,146/255f,208/255f);
            this.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;

            this.NavigationController.NavigationBar.TitleTextAttributes = new UIStringAttributes (){
                ForegroundColor = UIColor.White,
                Font = UIFont.FromName("System Bold",20.0f)
            };
            Title = name;
            this.NavigationItem.SetLeftBarButtonItem (new UIBarButtonItem(
                "Cancel", UIBarButtonItemStyle.Plain, (sender, args) => {
                    this.NavigationController.PopViewController(true);
                }), true);
            btn_close.TouchUpInside += (object sender, EventArgs e) => {

                this.NavigationController.PopViewController(true);
            };
        }
Exemplo n.º 3
0
		public override NSCachedUrlResponse CachedResponseForRequest (NSUrlRequest request)
		{
			var uri = (Uri) request.Url;
			int index;

			if ((index = related.IndexOf (uri)) != -1) {
				var part = related[index] as MimePart;

				if (part != null) {
					var mimeType = part.ContentType.MimeType;
					var charset = part.ContentType.Charset;
					NSUrlResponse response;
					NSData data;

					using (var content = part.ContentObject.Open ())
						data = NSData.FromStream (content);

					response = new NSUrlResponse (request.Url, mimeType, (int) data.Length, charset);

					return new NSCachedUrlResponse (response, data);
				}
			}

			return base.CachedResponseForRequest (request);
		}
Exemplo n.º 4
0
		private void SetupUserInterface ()
		{
			scrollView = new UIScrollView {
				BackgroundColor = UIColor.Clear.FromHexString ("#094074", 1.0f),
				Frame = new CGRect (0, 0, Frame.Width, Frame.Height * 2)
			};

			licensureLabel = new UILabel {
				Font = UIFont.FromName ("SegoeUI-Light", 25f),
				Frame = new CGRect (0, 20, Frame.Width, 35),
				Text = "Open-Source",
				TextAlignment = UITextAlignment.Center,
				TextColor = UIColor.White
			};

			string localHtmlUrl = Path.Combine (NSBundle.MainBundle.BundlePath, "Licensure.html");
			var url = new NSUrl (localHtmlUrl, false);
			var request = new NSUrlRequest (url);

			webView = new UIWebView () {
				Frame = new CGRect (0, 55, Frame.Width, Frame.Height - 55)
			};
			webView.LoadRequest (request);

			scrollView.ContentSize = new CGSize (Frame.Width, Frame.Height * 2);

			scrollView.Add (licensureLabel);
			scrollView.Add (webView);
			Add (scrollView);
		}
Exemplo n.º 5
0
        bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            const string scheme = "hybrid:";

            if (request.Url.Scheme != scheme.Replace (":", ""))
                return true;

            // This handler will treat everything between the protocol and "?"
            // as the method name.  The querystring has all of the parameters.
            var resources = request.Url.ResourceSpecifier.Split ('?');
            var method = resources [0];
            var parameters = System.Web.HttpUtility.ParseQueryString (resources [1]);

            if (method == "UpdateLabel") {
                var textbox = parameters ["textbox"];

                // Add some text to our string here so that we know something
                // happened on the native part of the round trip.
                var prepended = string.Format ("C# says: {0}", textbox);

                // Build some javascript using the C#-modified result
                var js = string.Format ("SetLabelText('{0}');", prepended);

                webView.EvaluateJavascript (js);
            }

            return false;
        }
Exemplo n.º 6
0
 public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
 {
     bool shouldStart = true;
     string url = request.Url.ToString();
     if (url.Contains("js-frame"))
     {
         shouldStart = false;
         string pendingArgs = bridge.webBrowser.EvaluateJavascript("window.locationMessenger.pendingArg.toString();");
         // Using JsonConvert.Deserialze<string[]> blows up under MonoTouch, so manually build the array of args instead
         JArray argsJArray = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(pendingArgs);
         string[] args = new string[argsJArray.Count];
         for (int i = 0; i < argsJArray.Count; i++)
             args[i] = (string)argsJArray[i];
         if (args[0] == "HandleScriptPropertyChanged")
         {
             if (args.Length == 3)
                 bridge.HandleScriptPropertyChanged(args[1], args[2], null);
             else
                 bridge.HandleScriptPropertyChanged(args[1], args[2], args[3]);
         }
         else if (args[0] == "InvokeViewModelIndexMethod")
             bridge.InvokeViewModelMethod(args[1], args[2], args[3]);
         else if (args[0] == "InvokeViewModelMethod")
             bridge.InvokeViewModelMethod(args[1], args[2]);
         else if (args[0] == "HandleDocumentReady")
             bridge.HandleDocumentReady();
         else if (args[0] == "HostLog")
             bridge.HostLog(args[1]);
         else
             SpinnakerConfiguration.CurrentConfig.Log(SpinnakerLogLevel.Error,"Ignoring unrecognized call from javascript for [" + args[0] + "] - this means that javascript in the view is trying to reach the host but with bad arguments");
     }
     return shouldStart;
 }
        public void DownloadImage(string url)
        {
            indicatorView.StartAnimating();
            NSUrlRequest request = new NSUrlRequest(new NSUrl(url));

            new NSUrlConnection(request, new ConnectionDelegate(this), true);
        }
Exemplo n.º 8
0
        private bool ShouldStartLoad (NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            if (request.Url.AbsoluteString.StartsWith("app://resize"))
            {
                try
                {
                    var size = WebView.EvaluateJavascript("size();");
                    if (size != null)
                        nfloat.TryParse(size, out _height);

                    if (HeightChanged != null)
                        HeightChanged(_height);
                }
                catch
                {
                }

                return false;
            }

            if (!request.Url.AbsoluteString.StartsWith("file://"))
            {
                if (UrlRequested != null)
                    UrlRequested(request.Url.AbsoluteString);
                return false;
            }

            return true;
        }
        public void Open(string url, string protocol = null, string authToken = null)
        {
            try
            {
                if (_client != null)
                    Close();

                NSUrlRequest req = new NSUrlRequest(new NSUrl(url));
                if (!string.IsNullOrEmpty(authToken))
                {
                    NSMutableUrlRequest mutableRequest = new NSMutableUrlRequest(new NSUrl(url));
                    mutableRequest["Authorization"] = authToken;
                    req = (NSUrlRequest)mutableRequest.Copy();
                }

                if (string.IsNullOrEmpty(protocol))
                    _client = new WebSocket(req);
                else
                    _client = new WebSocket(req, new NSObject[] { new NSString(protocol) });

                _client.ReceivedMessage += _client_ReceivedMessage;
                _client.WebSocketClosed += _client_WebSocketClosed;
                _client.WebSocketFailed += _client_WebSocketFailed;
                _client.WebSocketOpened += _client_WebSocketOpened;

                _client.Open();
            }
            catch (Exception ex)
            {
                OnError(ex.Message);
            }
        }
Exemplo n.º 10
0
		public async Task<nuint> DownloadFileAsync (Uri url, string destination)
		{
			this.Url = url.AbsoluteUri;
			if (downloadTask != null)
				return downloadTask.TaskIdentifier;
			if (session == null) {
				Initalize ();
			}
			Destination = destination;

			SessionId = session.Configuration.Identifier;
			if (!BackgroundDownloadManager.Tasks.TryGetValue (url.AbsoluteUri, out Tcs)) {
				Tcs = new TaskCompletionSource<bool> ();
				BackgroundDownloadManager.Tasks.Add (url.AbsoluteUri, Tcs);
				using (var request = new NSUrlRequest (new NSUrl (url.AbsoluteUri))) {
					downloadTask = session.CreateDownloadTask (request);
					downloadTask.Resume ();
				}
			}

			BackgroundDownloadManager.AddController (this.Url, this);

			await Tcs.Task;

			return downloadTask.TaskIdentifier; 
		}
		public bool RequestImage(string url, IImageUpdated receiver) {

			var local = RequestLocalImage(url);

			if (local != null) {
				receiver.UpdatedImage(url, local);
				return true;
			}

			if (pendingRequests.ContainsKey(url)){
				pendingRequests[url].Add(receiver);
			} else {
				pendingRequests.Add(url, new List<IImageUpdated>(){receiver});
			}
			NSUrlRequest req = new NSUrlRequest(new NSUrl(url), NSUrlRequestCachePolicy.ReturnCacheDataElseLoad, 10);
			new UrlConnection("img"+url, req, (UIImage img)=>{
				var surl = url;
				cache[surl] = img;
				var imgreq = pendingRequests[surl];
				foreach (var v in imgreq)
					v.UpdatedImage(surl, img);
				pendingRequests.Remove(surl);

			});
			return false;

		}
Exemplo n.º 12
0
        public static UIViewController AudioSelected(ApiNode apiNode)
        {
            var url = apiNode["videoSrc1"];

            if (apiNode["contentNode"] != null)
            {
                url = apiNode[apiNode["contentNode"]];
            }

            //var videoController = new UIVideoController(url);

            //videoController.NavigationItem.Title = apiNode.Title;

            //return videoController;

            var vc = new UIViewController();

            var webView = new UIWebView(UIScreen.MainScreen.Bounds)
            {
                BackgroundColor = UIColor.White,
                ScalesPageToFit = true,
                AutoresizingMask = UIViewAutoresizing.All
            };

            var request = new NSUrlRequest(new NSUrl(url), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 60);

            webView.LoadRequest(request);

            vc.NavigationItem.Title = apiNode.Title;

            vc.View.AutosizesSubviews = true;
            vc.View.AddSubview(webView);

            return vc;
        }
Exemplo n.º 13
0
		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);
			
			var urlRequest = new NSUrlRequest (new NSUrl (START_URL));
			_webView.LoadRequest (urlRequest);
		}
Exemplo n.º 14
0
		public NSUrlConnectionWrapper(NSUrlRequest request, EscozUrlStreamDelegate del) : base(request, del, true)
		{
			if (Connections.ContainsKey(del.Name)) {
				KillConnection(del.Name);
			}
			Connections.Add(del.Name, this);			
		}		
Exemplo n.º 15
0
		public NSUrlConnectionWrapper(string name, NSUrlRequest request, Action<Stream> success, Action failure)
			: base(request, new EscozUrlStreamDelegate(name, success, failure), true) {
			if (Connections.ContainsKey(name)) {
				KillConnection(name);
			}
			Connections.Add(name, this);
		}		
		void DownloadUsingNSUrlRequest (object sender, EventArgs e)
		{
			var downloadedDelegate = new CustomDelegate(this);

			var req = new NSUrlRequest(new NSUrl("http://ch3cooh.hatenablog.jp/"));
			NSUrlConnection connection = new NSUrlConnection(req, downloadedDelegate);
			connection.Start();
		} 
		protected override void RequestStarted (NSUrlRequest request)
		{
			if(request.Url.AbsoluteString.TrimEnd('/').Equals(DeniedUrl))
			{
				_cancelled ();
				this.DismissViewController (true, null);
			}
		}
Exemplo n.º 18
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad ();
     NSUrl url = new NSUrl (_urlAddress);
     NSUrlRequest request = new NSUrlRequest (url);
     this.webView.LoadRequest (request);
     // Perform any additional setup after loading the view, typically from a nib.
 }
Exemplo n.º 19
0
 public Comms(string name, NSUrlRequest request, Action<string> success, Action failure)
     : base(request, new CommsDelegate(name, success, failure), true)
 {
     if (Connections.ContainsKey (name)) {
         KillConnection (name);
     }
     Connections.Add (name, this);
 }
Exemplo n.º 20
0
		public override void ViewDidAppear(bool animated)
		{
			base.ViewDidAppear(animated);
			
			var req = new NSUrlRequest(new NSUrl(@""));
			_WebView.LoadRequest(req);
				
			
		}
Exemplo n.º 21
0
 public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
 {
     webView.UserInteractionEnabled = false;
     _cookieWebView.OnNavigating(new CookieNavigationEventArgs
     {
         Url = request.Url.AbsoluteString
     });
     return true;
 }
Exemplo n.º 22
0
		public UrlConnection(string name, NSUrlRequest request, Action<string> success, Action failure, Action<NSUrlConnection, NSUrlAuthenticationChallenge> challenge) : base(request, new UrlDelegate(name, success, failure, challenge), true)
		{
			if (Connections.ContainsKey(name))
			{
				KillConnection(name);
			}

			Connections.Add(name, this);
		}
Exemplo n.º 23
0
		public void Btn_TouchUpInside(object sender,EventArgs e)
		{
			if (!string.IsNullOrEmpty (this.txt.Text)) {

				NSUrl url = new NSUrl (this.txt.Text);
				NSUrlRequest request = new NSUrlRequest (url);
				this.webView.LoadRequest (request);
			}
		}
Exemplo n.º 24
0
		public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
		{
			if (navigationType == UIWebViewNavigationType.LinkClicked) {
				UIApplication.SharedApplication.OpenUrl (request.Url);
				return false;
			}

			return true;
		}
        public new static bool CanInitWithRequest(NSUrlRequest request)
        {
            if (request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase))
            {
                return GetProperty("MsalCustomUrlProtocol", request) == null;
            }

            return false;
        }
Exemplo n.º 26
0
        public IPhoneNSUrlProtocol(NSUrlRequest request, NSCachedUrlResponse cachedResponse, INSUrlProtocolClient client)
            : base(request, cachedResponse, client)
        {
            //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneNSUrlProtocol - Init with Request");

            serviceLocator = IPhoneServiceLocator.GetInstance ();
            serviceURIHandler = new IPhoneServiceURIHandler (serviceLocator);
            resourceURIHandler = new IPhoneResourceHandler (ApplicationSource.FILE);
            serviceInvocationManager = new ServiceInvocationManager ();
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            var loginRequest = new OauthLoginRequest(config.ClientID);
            var loginUri = unauthenticatedClient.Oauth.GetGitHubLoginUrl(loginRequest);
            var nsUrlRequest = new NSUrlRequest(new NSUrl(loginUri.OriginalString));

            webView.LoadStarted += HandleLoadStarted;
            webView.LoadRequest(nsUrlRequest);
        }
Exemplo n.º 28
0
        public TweetDetailsScreen(BL.Tweet showTweet)
            : base()
        {
            tweet = showTweet;

            View.BackgroundColor = UIColor.White;

            user = new UILabel () {
                TextAlignment = UITextAlignment.Left,
                Font = UIFont.FromName("Helvetica-Light",AppDelegate.Font16pt),
                BackgroundColor = UIColor.FromWhiteAlpha (0f, 0f)
            };
            handle = new UnderlineLabel () {
                TextAlignment = UITextAlignment.Left,
                Font = UIFont.FromName("Helvetica-Light",AppDelegate.Font9pt),
                TextColor = AppDelegate.ColorTextLink,

                BackgroundColor = UIColor.FromWhiteAlpha (0f, 0f)
            };
            handleButton = UIButton.FromType (UIButtonType.Custom);
            handleButton.TouchUpInside += (sender, e) => {
                var url = new NSUrl(tweet.AuthorUrl);
                var request = new NSUrlRequest(url);
                if (AppDelegate.IsPhone)
                    NavigationController.PushViewController (new WebViewController (request), true);
                else
                    PresentModalViewController (new WebViewController(request), true);
            };
            date = new UILabel () {
                TextAlignment = UITextAlignment.Left,
                Font = UIFont.FromName("Helvetica-Light",AppDelegate.Font9pt),
                TextColor = UIColor.DarkGray,
                BackgroundColor = UIColor.FromWhiteAlpha (0f, 0f)
            };

            image = new UIImageView();

            webView = new UIWebView();
            webView.Delegate = new WebViewDelegate(this);
            try { // iOS5 only
                webView.ScrollView.ScrollEnabled = false;
                webView.ScrollView.Bounces = false;
            } catch {}

            View.AddSubview (user);
            View.AddSubview (handle);
            View.AddSubview (handleButton);
            View.AddSubview (image);
            View.AddSubview (date);
            View.AddSubview (webView);

            LayoutSubviews();
            if (tweet != null)
                Update ();
        }
        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            webView = new WKWebView (View.Frame, new WKWebViewConfiguration ());
            View.AddSubview (webView);

            var url = new NSUrl ("https://evolve.xamarin.com");
            var request = new NSUrlRequest (url);
            webView.LoadRequest (request);
        }
Exemplo n.º 30
0
 /********************************************************************************
  *customus functions
  ********************************************************************************/
 /********************************************************************************
 *Views initializations
 ********************************************************************************/
 public void initWebView()
 {
     WebView = new UIWebView (new RectangleF(0f*Device.screenWidthP,0f*Device.screenHeightP,100f*Device.screenWidthP, 100f*Device.screenHeightP));
     WebView.ScalesPageToFit =true;
     if (!url.ToLower ().Contains ("https://")) {
         NavigationController.PopViewController (true);
     } else {
         var UrlRequest = new NSUrlRequest (new NSUrl (url));
         WebView.LoadRequest(UrlRequest);
     }
 }
Exemplo n.º 31
0
        bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            var scheme = "hybrid:";

            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            if (request.Url.Scheme != scheme.Replace(":", ""))
            {
                return(true);
            }

            // This handler will treat everything between the protocol and "?"
            // as the method name.  The querystring has all of the parameters.
            var resources  = request.Url.ResourceSpecifier.Split('?');
            var method     = resources [0];
            var parameters = System.Web.HttpUtility.ParseQueryString(resources[1]);             // breaks if ? not present (ie no params)

            if (method == "")
            {
                var template = new TodoView()
                {
                    Model = new TodoItem()
                };
                var page = template.GenerateString();
                webView.LoadHtmlString(page, NSBundle.MainBundle.BundleUrl);
            }
            else if (method == "ViewTask")
            {
                var id       = parameters ["todoid"];
                var model    = App.Database.GetItem(Convert.ToInt32(id));
                var template = new TodoView()
                {
                    Model = model
                };
                var page = template.GenerateString();
                webView.LoadHtmlString(page, NSBundle.MainBundle.BundleUrl);
            }
            else if (method == "TweetAll")
            {
                var todos   = App.Database.GetItemsNotDone();
                var totweet = "";
                foreach (var t in todos)
                {
                    totweet += t.Name + ",";
                }
                if (totweet == "")
                {
                    totweet = "there are no tasks to tweet";
                }
                else
                {
                    totweet = "Still do to:" + totweet;
                }
                var tweetController = new TWTweetComposeViewController();
                tweetController.SetInitialText(totweet);
                PresentModalViewController(tweetController, true);
            }
            else if (method == "TextAll")
            {
                if (MFMessageComposeViewController.CanSendText)
                {
                    var todos  = App.Database.GetItemsNotDone();
                    var totext = "";
                    foreach (var t in todos)
                    {
                        totext += t.Name + ",";
                    }
                    if (totext == "")
                    {
                        totext = "there are no tasks to text";
                    }

                    MFMessageComposeViewController message =
                        new MFMessageComposeViewController();
                    message.Finished += (sender, e) => {
                        e.Controller.DismissViewController(true, null);
                    };
                    //message.Recipients = new string[] { receiver };
                    message.Body = totext;
                    PresentModalViewController(message, true);
                }
                else
                {
                    new UIAlertView("Sorry", "Cannot text from this device", null, "OK", null).Show();
                }
            }
            else if (method == "TodoView")
            {
                // the editing form
                var button = parameters ["Button"];
                if (button == "Save")
                {
                    var id    = parameters ["id"];
                    var name  = parameters ["name"];
                    var notes = parameters ["notes"];
                    var done  = parameters ["done"];

                    var todo = new TodoItem {
                        ID    = Convert.ToInt32(id),
                        Name  = name,
                        Notes = notes,
                        Done  = (done == "on")
                    };

                    App.Database.SaveItem(todo);
                    NavigationController.PopToRootViewController(true);
                }
                else if (button == "Delete")
                {
                    var id = parameters ["id"];

                    App.Database.DeleteItem(Convert.ToInt32(id));
                    NavigationController.PopToRootViewController(true);
                }
                else if (button == "Cancel")
                {
                    NavigationController.PopToRootViewController(true);
                }
                else if (button == "Speak")
                {
                    var name  = parameters ["name"];
                    var notes = parameters ["notes"];
                    Speech.Speak(name + " " + notes);
                }
            }
            return(false);
        }
Exemplo n.º 32
0
 public override NSUrlSessionDownloadTask CreateDownloadTask(NSUrlRequest request, NSUrlDownloadSessionResponse completionHandler)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 33
0
 public static new bool CanInitWithRequest(NSUrlRequest request)
 {
     Called_CanInitWithRequest = true;
     return(true);
 }
Exemplo n.º 34
0
 public CustomUrlProtocol(NSUrlRequest request, NSCachedUrlResponse cachedResponse, INSUrlProtocolClient client)
     : base(request, cachedResponse, client)
 {
     custom_url_protocol_instance = this;
 }
            /// <summary>
            /// Whether the UIWebView should begin loading data.
            /// </summary>
            /// <returns><c>true</c>, if start load was shoulded, <c>false</c> otherwise.</returns>
            /// <param name="webView">Web view.</param>
            /// <param name="request">Request.</param>
            /// <param name="navigationType">Navigation type.</param>
            public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
            {
                NSUrl nsUrl = request.Url;

                string msg = null;

                #if DEBUG
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"UIWebViewDelegate.ShouldStartLoad ");
                sb.AppendLine($"        nsUrl.AbsoluteString = {nsUrl.AbsoluteString}");
                sb.AppendLine($"        WebViewConfiguration.IOS.UserAgent = {WebViewConfiguration.IOS.UserAgent}");
                System.Diagnostics.Debug.WriteLine(sb.ToString());
                #endif

                WebAuthenticator         wa  = null;
                WebRedirectAuthenticator wra = null;

                wa  = this.controller.authenticator as WebAuthenticator;
                wra = this.controller.authenticator as WebRedirectAuthenticator;

                #if DEBUG
                if (wa != null)
                {
                    msg = String.Format("WebAuthenticatorController.authenticator as WebAuthenticator");
                    System.Diagnostics.Debug.WriteLine(msg);
                }
                if (wra != null)
                {
                    msg = String.Format("WebAuthenticatorController.authenticator as WebRedirectAuthenticator");
                    System.Diagnostics.Debug.WriteLine(msg);
                }

                msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", nsUrl.AbsoluteString);
                System.Diagnostics.Debug.WriteLine(msg);
                #endif

                bool is_loadable_url = false;
                if (nsUrl != null && !controller.authenticator.HasCompleted)
                {
                    Uri url;
                    if (Uri.TryCreate(nsUrl.AbsoluteString, UriKind.Absolute, out url))
                    {
                        string host   = url.Host.ToLower();
                        string scheme = url.Scheme;

                        #if DEBUG
                        msg = String.Format("WebAuthenticatorController.ShouldStartLoad {0}", url.AbsoluteUri);
                        System.Diagnostics.Debug.WriteLine(msg);
                        msg = string.Format("                          Host   = {0}", host);
                        System.Diagnostics.Debug.WriteLine(msg);
                        msg = string.Format("                          Scheme = {0}", scheme);
                        System.Diagnostics.Debug.WriteLine(msg);
                        #endif

                        if (host == "localhost" || host == "127.0.0.1" || host == "::1")
                        {
                            is_loadable_url = false;
                            this.controller.DismissViewControllerAsync(true);
                        }
                        else
                        {
                            is_loadable_url = true;
                        }

                        controller.authenticator.OnPageLoading(url);
                    }
                }

                if (wra != null)
                {
                    // TODO: class refactoring
                    // OAuth2Authenticator is WebRedirectAuthenticator wra
                    wra.IsLoadableRedirectUri = is_loadable_url;
                    return(wra.IsLoadableRedirectUri);
                }
                else if (wa != null)
                {
                    // TODO: class refactoring
                    // OAuth1Authenticator is WebRedirectAuthenticator wra
                    return(is_loadable_url);
                }

                return(false);
            }
Exemplo n.º 36
0
 public override NSUrlSessionUploadTask CreateUploadTask(NSUrlRequest request, NSData bodyData, NSUrlSessionResponse completionHandler)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 37
0
        /// <summary>
        /// Shoulds the start load.
        /// </summary>
        /// <returns><c>true</c>, if start load was shoulded, <c>false</c> otherwise.</returns>
        /// <param name="webView">Web view.</param>
        /// <param name="request">Request.</param>
        /// <param name="navigationType">Navigation type.</param>
        public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            string urlString = request.Url.AbsoluteString;            //"looseleaf:kp//opendocument?dpsi=02I6&refpt=2006A69S65&remotekey1=REFPTID" for example

            //parse request url
            int    endPostOfProtocal = urlString.IndexOf("://");
            string protocalStr       = "";     //"http", "looseleaf" etc.
            string addressStr        = "";     //"opendocument?dpsi=02I6&refpt=2006A69S65&remotekey1=REFPTID" for example
            string functionStr       = "";     //"opendocument", "loadpage" etc
            Dictionary <string, string> requestParams = new Dictionary <string, string>();

            if (endPostOfProtocal > 0)
            {
                protocalStr = urlString.Substring(0, endPostOfProtocal);
                addressStr  = urlString.Substring(endPostOfProtocal + 3);

                if (addressStr != null)
                {
                    string[] addressStrArr = addressStr.Split(new char[1] {
                        '?'
                    });
                    functionStr = addressStrArr.Length > 0 ? addressStrArr [0] : "";

                    if (addressStrArr.Length >= 2)
                    {
                        string   paramsStr = addressStrArr [1];
                        string[] paramsArr = paramsStr.Split(new char[1] {
                            '&'
                        });
                        foreach (string aParamPair in paramsArr)
                        {
                            string[] nameValue = aParamPair.Split(new char[1] {
                                '='
                            });
                            if (nameValue.Length >= 2)
                            {
                                requestParams.Add(nameValue [0], nameValue [1]);
                            }
                        }
                    }
                }
            }
            if (navigationType == UIWebViewNavigationType.LinkClicked)
            {
                var bookId    = AppDataUtil.Instance.GetCurrentPublication().BookId;
                var hyperLink = PublicationContentUtil.Instance.BuildHyperLink(bookId, urlString);
                switch (hyperLink.LinkType)
                {
                case HyperLinkType.IntraHyperlink:
                    var Intra = hyperLink as IntraHyperlink;
                    var tocId = Intra.TOCID;
                    AppDataUtil.Instance.SetOpendTOC(AppDataUtil.Instance.GetTOCNodeByID(tocId));
                    AppDataUtil.Instance.SetHighlightedTOCNode(AppDataUtil.Instance.GetTOCNodeByID(tocId));
                    AppDataUtil.Instance.ScrollToHtmlTagId = Intra.Refpt;
                    AppDataUtil.Instance.AddBrowserRecord(new ContentBrowserRecord(AppDataUtil.Instance.GetCurrentPublication().BookId, tocId, 0));                     //add browser record
                    break;

                case HyperLinkType.InternalHyperlink:
                    var inter = hyperLink as InternalHyperlink;
                    var booId = inter.BookID;
                    var TocId = inter.TOCID;
                    AppDataUtil.Instance.ScrollToHtmlTagId = inter.Refpt;
                    List <Publication> cachedPublicationList = PublicationUtil.Instance.GetPublicationOffline();
                    var publication = cachedPublicationList.FirstOrDefault(o => o.BookId == booId);
                    AppDataUtil.Instance.SetCurrentPublication(publication);
                    AppDataUtil.Instance.SetOpendTOC(AppDataUtil.Instance.GetTOCNodeByID(TocId));
                    AppDataUtil.Instance.SetHighlightedTOCNode(AppDataUtil.Instance.GetTOCNodeByID(TocId));

                    break;

                case HyperLinkType.ExternalHyperlink:
                    var    External  = hyperLink as ExternalHyperlink;
                    string stringUrl = External.Url;
                    UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(stringUrl));
                    break;

                case HyperLinkType.AttachmentHyperlink:
                    var AttachMent = hyperLink as AttachmentHyperlink;
                    if (AttachMent != null)
                    {
                        string       targetFileName = AttachMent.TargetFileName;
                        string       appRootPath    = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/" + targetFileName;
                        NSUrl        url            = new NSUrl(appRootPath);
                        NSUrlRequest requestUrl     = NSUrlRequest.FromUrl(url);
                        AppDataUtil.Instance.AddBrowserRecord(new DocumentBrowserRecord(AppDataUtil.Instance.GetCurrentPublication().BookId, AppDataUtil.Instance.GetOpendTOC().ID, 0, 0, AttachMent));
                        webView.LoadRequest(requestUrl);
                        AppDisplayUtil.Instance.contentVC.ContentNavigationItem.LeftBarButtonItems[1].Enabled = true;
                    }
                    break;
                }
            }

            if (protocalStr == "looseleaf")
            {
                switch (functionStr)
                {
                case "loadpage":
                    AppDataUtil.Instance.ScrollToTOC(AppendPageContent, webView, requestParams ["page"], Convert.ToInt32(requestParams ["tocid"]));
                    TOCNode targetNode = AppDataUtil.Instance.GetNextOfTOCNodeWithId(Convert.ToInt32(requestParams ["tocid"]), requestParams ["page"]);
                    if (targetNode != null)
                    {
                        string js = string.Format("setLoadingTOCTitle(\"{0}\",\"{1}\",\"{2}\")", targetNode.ID, targetNode.Title, requestParams ["page"]);
                        webView.EvaluateJavascript(js);
                    }
                    else
                    {
                        webView.EvaluateJavascript(string.Format("setLoadingTOCTitle(\"-1\",\"You can't scroll to a new page\", \"{0}\")", requestParams ["page"]));
                    }
                    break;

                case "highlighttoc":
                    if (requestParams ["tocid"] != AppDataUtil.Instance.GetHighlightedTOCNode().ID.ToString())
                    {
                        try{
                            TOCNode toBeHighlightedTOCNode = AppDataUtil.Instance.GetTOCNodeByID(Convert.ToInt32(requestParams ["tocid"]));
                            AppDataUtil.Instance.SetHighlightedTOCNode(toBeHighlightedTOCNode);
                            AppDisplayUtil.Instance.TOCVC.SetHighlightedTOCNode(toBeHighlightedTOCNode);
                        }catch (Exception e) {
                            Insights.Report(e, new Dictionary <string, string> {
                                { "Exception summary", "Highlight next or previous toc when scrolling up or down" },
                                { "Publication ID", AppDataUtil.Instance.GetCurrentPublication().BookId.ToString() },
                                { "Publication Name", AppDataUtil.Instance.GetCurrentPublication().Name },
                                { "Country", GlobalAccess.Instance.CurrentUserInfo.Country.CountryName },
                                { "Email", GlobalAccess.Instance.CurrentUserInfo.Email },
                            });
                        }
                    }
                    break;

                case "setCurrentPBOPageNum":
                    var PageNum = requestParams["pageNum"];
                    NSNotificationCenter.DefaultCenter.PostNotificationName("inputPageNumber", this, new NSDictionary("page", PageNum));

                    break;
                }
                return(false);
            }

            return(true);
        }
Exemplo n.º 38
0
 public void useUrlSession(NSUrlRequest request)
 {
     NSUrlProtocol.RegisterClass(new ObjCRuntime.Class(typeof(CustomUrlProtocol)));
     webView.LoadRequest(request);
 }
Exemplo n.º 39
0
            public override void DecidePolicyForNavigation(WebView webView, NSDictionary actionInformation, NSUrlRequest request, WebFrame frame, NSObject decisionToken)
            {
                switch ((WebNavigationType)((NSNumber)actionInformation [WebPolicyDelegate.WebActionNavigationTypeKey]).Int32Value)
                {
                case WebNavigationType.BackForward:
                case WebNavigationType.FormResubmitted:
                case WebNavigationType.FormSubmitted:
                    WebPolicyDelegate.DecideIgnore(decisionToken);
                    break;

                case WebNavigationType.LinkClicked:
                    NSWorkspace.SharedWorkspace.OpenUrl(actionInformation[WebPolicyDelegate.WebActionOriginalUrlKey] as NSUrl);
                    WebPolicyDelegate.DecideIgnore(decisionToken);
                    break;

                case WebNavigationType.Other:
                case WebNavigationType.Reload:
                    WebPolicyDelegate.DecideUse(decisionToken);
                    break;
                }
            }
Exemplo n.º 40
0
        void setUpViews()
        {
            this.Title = "Tunneling";
            CGSize mainScreenSize = UIScreen.MainScreen.Bounds.Size;

            float offsetXForUIElements = 10.0f;
            float widthForUIElements   = (float)(mainScreenSize.Width - (offsetXForUIElements * 2.0f));
            float btnHeight            = 40;

            //uisegmented control
            string[]           stringArray           = { "UIWebView", "NSUrlSession" };
            CGRect             segmentedControlFrame = new CGRect(offsetXForUIElements, 100, widthForUIElements, btnHeight);
            UISegmentedControl segmentedControl      = new UISegmentedControl(stringArray);

            segmentedControl.Frame           = segmentedControlFrame;
            segmentedControl.SelectedSegment = 0;
            View.AddSubview(segmentedControl);

            //tunnel url text field

            urlTextField                        = new UITextField();
            urlTextField.Frame                  = new CGRect(offsetXForUIElements, 150, widthForUIElements, btnHeight);
            urlTextField.Placeholder            = "Enter the url with http/https ";
            urlTextField.BackgroundColor        = UIColor.LightGray;
            urlTextField.UserInteractionEnabled = true;
            urlTextField.Layer.CornerRadius     = 3.5f;
            urlTextField.Layer.BorderWidth      = 1.0f;
            urlTextField.Layer.BorderColor      = UIColor.DarkGray.CGColor;
            View.AddSubview(urlTextField);

            //UIBarButtonItem - GO button
            UIBarButtonItem rightBarButtonItem = new UIBarButtonItem("GO", UIBarButtonItemStyle.Done, null);

            rightBarButtonItem.Clicked += (object sender, System.EventArgs e) =>
            {
                urlTextField.ResignFirstResponder();
                if (urlTextField.Text != "")
                {
                    NSUrlRequest request = createRequestFromString(urlTextField.Text);
                    if (request != null)
                    {
                        if (segmentedControl.SelectedSegment == 0)
                        {
                            useWebView(request);
                        }
                        else if (segmentedControl.SelectedSegment == 1)
                        {
                            useUrlSession(request);
                        }
                    }
                }
                else
                {
                    showAlert("Please enter the URL");
                }
            };
            this.NavigationItem.RightBarButtonItem = rightBarButtonItem;

            //uiwebview
            CGRect webViewFrame = new CGRect(offsetXForUIElements, 200, widthForUIElements, 300f);

            webView = new UIWebView(webViewFrame);

            webView.BackgroundColor    = UIColor.White;
            webView.Layer.CornerRadius = 10;
            webView.Layer.BorderColor  = UIColor.Black.CGColor;
            webView.Layer.BorderWidth  = 3.0f;

            View.AddSubview(webView);
        }
Exemplo n.º 41
0
 public override void DecidePolicyForNavigation(WebView web_view, NSDictionary action_info,
                                                NSUrlRequest request, WebFrame frame, NSObject decision_token)
 {
     LinkClicked(request.Url.ToString());
 }
Exemplo n.º 42
0
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     completionHandler(sessionHandler.AllowAutoRedirect ? newRequest : null);
 }
Exemplo n.º 43
0
        public void CreateDataTaskAsync()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            NSUrlSession session = NSUrlSession.SharedSession;
            var          url     = new NSUrl("https://www.microsoft.com");
            var          tmpfile = Path.GetTempFileName();

            File.WriteAllText(tmpfile, "TMPFILE");
            var file_url  = NSUrl.FromFilename(tmpfile);
            var file_data = NSData.FromFile(tmpfile);
            var request   = new NSUrlRequest(url);

            var completed = false;
            var timeout   = 30;

            /* CreateDataTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDataTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDataTask b");

            /* CreateDownloadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDownloadTask a");


            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDownloadTask b");

            /* CreateUploadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    var uploadRequest        = new NSMutableUrlRequest(url);
                    uploadRequest.HttpMethod = "POST";
                    await session.CreateUploadTaskAsync(uploadRequest, file_url);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    var uploadRequest        = new NSMutableUrlRequest(url);
                    uploadRequest.HttpMethod = "POST";
                    await session.CreateUploadTaskAsync(uploadRequest, file_data);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask b");
        }
Exemplo n.º 44
0
        public TweetDetailsScreen(BL.Tweet showTweet) : base()
        {
            tweet = showTweet;

            View.BackgroundColor = UIColor.White;

            user = new UILabel()
            {
                TextAlignment   = UITextAlignment.Left,
                Font            = UIFont.FromName("Helvetica-Light", AppDelegate.Font16pt),
                BackgroundColor = UIColor.FromWhiteAlpha(0f, 0f)
            };
            handle = new UnderlineLabel()
            {
                TextAlignment = UITextAlignment.Left,
                Font          = UIFont.FromName("Helvetica-Light", AppDelegate.Font9pt),
                TextColor     = AppDelegate.ColorTextLink,

                BackgroundColor = UIColor.FromWhiteAlpha(0f, 0f)
            };
            handleButton = UIButton.FromType(UIButtonType.Custom);
            handleButton.TouchUpInside += (sender, e) => {
                var url     = new NSUrl(tweet.AuthorUrl);
                var request = new NSUrlRequest(url);
                if (AppDelegate.IsPhone)
                {
                    NavigationController.PushViewController(new WebViewController(request), true);
                }
                else
                {
                    PresentModalViewController(new WebViewController(request), true);
                }
            };
            date = new UILabel()
            {
                TextAlignment   = UITextAlignment.Left,
                Font            = UIFont.FromName("Helvetica-Light", AppDelegate.Font9pt),
                TextColor       = UIColor.DarkGray,
                BackgroundColor = UIColor.FromWhiteAlpha(0f, 0f)
            };

            image = new UIImageView();

            webView          = new UIWebView();
            webView.Delegate = new WebViewDelegate(this);
            try {             // iOS5 only
                webView.ScrollView.ScrollEnabled = false;
                webView.ScrollView.Bounces       = false;
            } catch {}

            View.AddSubview(user);
            View.AddSubview(handle);
            View.AddSubview(handleButton);
            View.AddSubview(image);
            View.AddSubview(date);
            View.AddSubview(webView);

            LayoutSubviews();
            if (tweet != null)
            {
                Update();
            }
        }
Exemplo n.º 45
0
 public static new NSUrlRequest GetCanonicalRequest(NSUrlRequest forRequest)
 {
     return(forRequest);
 }
Exemplo n.º 46
0
 protected virtual bool ShouldStartLoad(NSUrlRequest request, UIWebViewNavigationType navigationType)
 {
     return(true);
 }
Exemplo n.º 47
0
 public new static NSUrlRequest GetCanonicalRequest(NSUrlRequest request)
 {
     return(request);
 }
Exemplo n.º 48
0
 /// <inheritdoc />
 protected override void NavigateCore(Uri absoluteUri)
 {
     using var nsUrl   = new NSUrl(absoluteUri.ToString());
     using var request = new NSUrlRequest(nsUrl);
     _webview.LoadRequest(request);
 }
Exemplo n.º 49
0
            public override void DecidePolicyForNavigation(
                WebView webView,
                NSDictionary actionInformation,
                NSUrlRequest request,
                WebFrame frame,
                NSObject decisionToken)
            {
                if (!initialNavigationPerformed)
                {
                    WebView.DecideUse(decisionToken);
                    initialNavigationPerformed = true;
                    return;
                }

                var originalRequestUrl = (NSUrl)actionInformation [WebActionOriginalUrlKey];

                if (originalRequestUrl.Scheme == "data")
                {
                    WebView.DecideUse(decisionToken);
                    return;
                }

                // Let iframes do their own navigation handling.
                if (frame != webView.MainFrame)
                {
                    if (originalRequestUrl.Scheme == "about")
                    {
                        WebView.DecideUse(decisionToken);
                    }
                    else
                    {
                        NSWorkspace.SharedWorkspace.OpenUrl(originalRequestUrl);
                        WebView.DecideIgnore(decisionToken);
                    }
                    return;
                }

                if (ScrollToElementWithId(webView, request.Url.Fragment))
                {
                    WebView.DecideIgnore(decisionToken);
                    return;
                }

                NSUrl workspaceUrl = null;

                try {
                    var resourceAction = ClientApp
                                         .SharedInstance
                                         .WebServer
                                         .TryGetLocalResourcePath(
                        originalRequestUrl,
                        out var localPath);

                    switch (resourceAction)
                    {
                    case ClientWebServer.ResourceAction.WorkbookResource:
                        workspaceUrl = NSUrl.FromFilename(localPath);
                        break;

                    case ClientWebServer.ResourceAction.ExternalResource:
                        workspaceUrl = originalRequestUrl;
                        break;
                    }
                } catch {
                    workspaceUrl = originalRequestUrl;
                }

                if (workspaceUrl != null)
                {
                    NSWorkspace.SharedWorkspace.OpenUrl(workspaceUrl);
                }

                WebView.DecideIgnore(decisionToken);
            }
Exemplo n.º 50
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, [BlockProxy(typeof(Trampolines.NIDActionArity1V1))] Action <NSUrlRequest> completionHandler)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 51
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     Called_WillPerformHttpRedirection = true;
     completionHandler(newRequest);
 }
Exemplo n.º 52
0
        public void HttpSample()
        {
            var req = new NSUrlRequest(new NSUrl(Application.WisdomUrl), NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 10);

            NSUrlConnection.FromRequest(req, this);
        }
Exemplo n.º 53
0
 public static new NSUrlRequest GetCanonicalRequest(NSUrlRequest request)
 {
     Called_GetCanonicalRequest = true;
     return(request);
 }
Exemplo n.º 54
0
 public UrlProtocol(NSUrlRequest request, NSCachedUrlResponse cachedResponse, NSUrlProtocolClient client)
     : base(request, cachedResponse, client)
 {
     this.Client = client;
 }
Exemplo n.º 55
0
 private void LoadAddressUrl()
 {
     var requestURL = NSUrl.FromString(addressTextField.Text);
     var request    = new NSUrlRequest(requestURL);
     var navigation = webView.LoadRequest(request);
 }
Exemplo n.º 56
0
 public override NSUrlSessionUploadTask CreateUploadTask(NSUrlRequest request)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 57
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.BackgroundColor = UIColor.White;

            _webView = new UIWebView((CGRect)View.Bounds);
            _webView.ShouldStartLoad = (wView, request, navType) =>
            {
                if (request == null)
                {
                    return(true);
                }

                string requestUrlString = request.Url.ToString();

                if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => CancelAuthentication(null, null));
                    requestUrlString = requestUrlString.Replace(BrokerConstants.BrowserExtPrefix, "https://");
                    DispatchQueue.MainQueue.DispatchAsync(
                        () => UIApplication.SharedApplication.OpenUrl(new NSUrl(requestUrlString)));
                    this.DismissViewController(true, null);
                    return(false);
                }

                if (requestUrlString.ToLower(CultureInfo.InvariantCulture).StartsWith(_callback.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, request.Url.ToString()));
                    this.DismissViewController(true, null);
                    return(false);
                }

                if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.CurrentCultureIgnoreCase))
                {
                    Uri    uri   = new Uri(requestUrlString);
                    string query = uri.Query;
                    if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase))
                    {
                        query = query.Substring(1);
                    }

                    Dictionary <string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null);
                    string responseHeader = PlatformPlugin.DeviceAuthHelper.CreateDeviceAuthChallengeResponse(keyPair).Result;

                    NSMutableUrlRequest newRequest = (NSMutableUrlRequest)request.MutableCopy();
                    newRequest.Url = new NSUrl(keyPair["SubmitUrl"]);
                    newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader;
                    wView.LoadRequest(newRequest);
                    return(false);
                }

                if (!request.Url.AbsoluteString.Equals("about:blank", StringComparison.CurrentCultureIgnoreCase) && !request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase))
                {
                    AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp);
                    result.Error            = MsalError.NonHttpsRedirectNotSupported;
                    result.ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported;
                    callbackMethod(result);
                    this.DismissViewController(true, null);
                    return(false);
                }


                return(true);
            };

            _webView.LoadFinished += delegate
            {
                // If the title is too long, iOS automatically truncates it and adds ...
                this.Title = _webView.EvaluateJavascript(@"document.title") ?? "Sign in";
            };

            View.AddSubview(_webView);

            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel,
                                                                        this.CancelAuthentication);

            NSUrlRequest startRequest = new NSUrlRequest(new NSUrl(this._url));

            _webView.LoadRequest(startRequest);

            // if this is false, page will be 'zoomed in' to normal size
            //webView.ScalesPageToFit = true;
        }
Exemplo n.º 58
0
 public void Redirected(NSUrlProtocol protocol, NSUrlRequest redirectedToEequest, NSUrlResponse redirectResponse)
 {
 }
Exemplo n.º 59
0
 public CustomProtocol(NSUrlRequest request, NSCachedUrlResponse cachedResponse, INSUrlProtocolClient client)
 {
 }
Exemplo n.º 60
0
        public void DecidePolicyForNavigation(WebKit.WebView webView, NSDictionary actionInformation, NSUrlRequest request, WebKit.WebFrame frame, WebKit.IWebPolicyDecisionListener decisionToken)
        {
            var navEvent = WebNavigationEvent.NewPage;

            if (actionInformation.ContainsKey(WebPolicyDelegate.WebActionNavigationTypeKey))
            {
                var navigationType = ((WebNavigationType)((NSNumber)actionInformation[WebPolicyDelegate.WebActionNavigationTypeKey]).Int32Value);
                switch (navigationType)
                {
                case WebNavigationType.BackForward:
                    navEvent = _lastBackForwardEvent;
                    break;

                case WebNavigationType.Reload:
                    navEvent = WebNavigationEvent.Refresh;
                    break;

                case WebNavigationType.FormResubmitted:
                case WebNavigationType.FormSubmitted:
                case WebNavigationType.LinkClicked:
                case WebNavigationType.Other:
                    navEvent = WebNavigationEvent.NewPage;
                    break;
                }
            }

            if (!_sentNavigating)
            {
                _lastEvent      = navEvent;
                _sentNavigating = true;
                var lastUrl = request.Url.ToString();
                var args    = new WebNavigatingEventArgs(navEvent, new UrlWebViewSource {
                    Url = lastUrl
                }, lastUrl);

                Element.SendNavigating(args);
                UpdateCanGoBackForward();
                if (!args.Cancel)
                {
                    decisionToken.Use();
                }

                _sentNavigating = false;
            }
        }