Beispiel #1
0
 // Convenience method taking a strong dictionary
 public static VTMultiPassStorage Create(
     VTMultiPassStorageCreationOptions options,
     NSUrl fileUrl = null,
     CMTimeRange? timeRange = null)
 {
     return Create (fileUrl, timeRange, options != null ? options.Dictionary : null);
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			UIBarButtonItem home = new UIBarButtonItem();
			home.Style = UIBarButtonItemStyle.Plain;
			home.Target = this;
			home.Image = UIImage.FromFile("Images/home.png");
			this.NavigationItem.RightBarButtonItem = home;
			UIViewController[] vistas = NavigationController.ViewControllers;
			home.Clicked += (sender, e) => {
				this.NavigationController.PopToViewController(vistas[0], true);
			};
			
			this.lblTitulo.Text = this.noticia.titulo;
			try{
				NSUrl nsUrl = new NSUrl (this.noticia.imagen);
				NSData data = NSData.FromUrl (nsUrl);
				this.imgNoticia.Image = UIImage.LoadFromData (data);
			}catch(Exception){
				this.imgNoticia.Image = Images.sinImagen;
			}
			if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone){
				this.txtDescripcion.Font = UIFont.SystemFontOfSize(10);
			}else{
				this.txtDescripcion.Font = UIFont.SystemFontOfSize(30);
			}
			this.txtDescripcion.Text = this.noticia.descripcion;
		}
Beispiel #3
0
        public CFBundle(NSUrl bundleUrl)
        {
            if (bundleUrl == null)
                throw new ArgumentNullException ("bundleUrl");

            this.handle = CFBundleCreate (IntPtr.Zero, bundleUrl.Handle);
        }
        public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl)
        {
            var tcs = new TaskCompletionSource<NSUrl>();

            NSUrl localDocDir = GetDocumentDirectoryUrl ();
            NSUrl toURL = localDocDir.Append (fromUrl.LastPathComponent, false);

            bool success = false;
            NSError coordinationError, copyError = null;
            NSFileCoordinator fileCoordinator = new NSFileCoordinator ();

            ThreadPool.QueueUserWorkItem (_ => {
                fileCoordinator.CoordinateReadWrite (fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => {
                    NSFileManager fileManager = new NSFileManager();
                    success = fileManager.Copy(src, dst, out copyError);

                    if (success) {
                        var attributes = new NSFileAttributes {
                            ExtensionHidden = true
                        };
                        fileManager.SetAttributes (attributes, dst.Path);
                        Console.WriteLine ("Copied file: {0} to: {1}.", src.AbsoluteString, dst.AbsoluteString);
                    }
                });

                // In your app, handle this gracefully.
                if (!success)
                    Console.WriteLine ("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString,
                        toURL.AbsoluteString, (coordinationError ?? copyError).Description);

                tcs.SetResult(toURL);
            });

            return tcs.Task;
        }
		private void LoadAlbumInformation ()
		{
			var albumUrlPath = "http://api.dribbble.com/" + _apiPath; 

			// Nimbus processors allow us to perform complex computations on a separate thread before
			// returning the object to the main thread. This is useful here because we perform sorting
			// operations and pruning on the results.
			var url = new NSUrl (albumUrlPath);
			var request = new NSMutableUrlRequest (url);

//			public delegate void ImageRequestOperationWithRequestSuccess1(UIImage image);
//			public delegate void ImageRequestOperationWithRequestSuccess2(NSUrlRequest request, NSHttpUrlResponse response, UIImage image);
//			public delegate void ImageRequestOperationWithRequestFailure(NSUrlRequest request, NSHttpUrlResponse response, NSError error);
//			public delegate UIImage ImageRequestOperationWithRequestProcessingBlock(UIImage image);
//			public delegate void AFJSONRequestOperationJsonRequestOperationWithRequestSuccess(NSUrlRequest request, NSHttpUrlResponse response, NSObject json);
//			public delegate void AFJSONRequestOperationJsonRequestOperationWithRequestFailure(NSUrlRequest request, NSHttpUrlResponse response, NSError error, NSObject json);
//			[BaseType (typeof (AFHTTPRequestOperation))]

			var albumRequest = AFJSONRequestOperation.JsonRequestOperationWithRequest (request, 
			                                                                           (req, res, json) => {
				BlockForAlbumProcessing (req, res, (NSDictionary)json);
			}, (req, resp, error, json) => {
				Console.WriteLine ("Error");
			});

			Queue.AddOperation (albumRequest);
		}
        public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
        {
            EventsTableCell cell = new EventsTableCell(cellIdentifier);
            try
            {
                cell = tableView.DequeueReusableCell(cellIdentifier) as EventsTableCell;

                if (cell == null)
                    cell = new EventsTableCell(cellIdentifier);
                string dt = tableItems[indexPath.Row].StartDate.ToString("d/MM") +" "+ tableItems[indexPath.Row].StartDate.ToLocalTime().ToShortTimeString() + " @ " + tableItems[indexPath.Row].Location;
                if (!String.IsNullOrEmpty(tableItems[indexPath.Row].LogoUrl))
                {
                    NSUrl nsUrl = new NSUrl(tableItems[indexPath.Row].LogoUrl);
                    NSData data = NSData.FromUrl(nsUrl);

                    if (data != null)
                        cell.UpdateCell(tableItems[indexPath.Row].Name, dt, new UIImage(data));
                    else
                        cell.UpdateCell(tableItems[indexPath.Row].Name, dt, new UIImage());
                }
                else
                    cell.UpdateCell(tableItems[indexPath.Row].Name, dt, new UIImage());

                OnGotCell();
                CellOn = indexPath.Row;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.iPhone);
            }
            return cell;
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			if (ArchitectView.IsDeviceSupported (AugmentedRealityMode.Geo))
			{
				arView = new ArchitectView (UIScreen.MainScreen.Bounds);
				View = arView;
			
				arView.SetLicenseKey ("YOUR-LICENSE-KEY");

				var absoluteWorldUrl = WorldOrUrl;

				if (!IsUrl)
					absoluteWorldUrl = NSBundle.MainBundle.BundleUrl.AbsoluteString + "ARchitectExamples/" + WorldOrUrl + "/index.html";

				var u = new NSUrl (absoluteWorldUrl);
				
				arView.LoadArchitectWorld (u);

			}
			else
			{
				var adErr = new UIAlertView ("Unsupported Device", "This device is not capable of running ARchitect Worlds. Requirements are: iOS 5 or higher, iPhone 3GS or higher, iPad 2 or higher. Note: iPod Touch 4th and 5th generation are only supported in WTARMode_IR.", null, "OK", null);
				adErr.Show ();
			}
		}
 public ImageLoaderStringElement(string caption,  NSAction tapped, NSUrl imageUrl, UIImage placeholder)
     : base(caption, tapped)
 {
     Placeholder = placeholder;
     ImageUrl = imageUrl;
     this.Accessory = UITableViewCellAccessory.None;
 }
Beispiel #9
0
        public void ShareUrl(object sender, Uri uri)
        {
            var item = new NSUrl(uri.AbsoluteUri);
            var activityItems = new NSObject[] { item };
            UIActivity[] applicationActivities = null;
            var activityController = new UIActivityViewController (activityItems, applicationActivities);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) 
            {
                var window = UIApplication.SharedApplication.KeyWindow;
                var pop = new UIPopoverController (activityController);

                var barButtonItem = sender as UIBarButtonItem;
                if (barButtonItem != null)
                {
                    pop.PresentFromBarButtonItem(barButtonItem, UIPopoverArrowDirection.Any, true);
                }
                else
                {
                    var rect = new CGRect(window.RootViewController.View.Frame.Width / 2, window.RootViewController.View.Frame.Height / 2, 0, 0);
                    pop.PresentFromRect (rect, window.RootViewController.View, UIPopoverArrowDirection.Any, true);
                }
            } 
            else 
            {
                var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                viewController.PresentViewController(activityController, true, null);
            }
        }
        public IObservable<Unit> Fetch (Request request)
        {
            return Observable.Create<Unit> (o => {
                var description = request.DescriptionAs<ScaledDescription> ();
                var url = new NSUrl (description.AbsoluteSourceUrl.AbsoluteUri);
                var disp = new CancellationDisposable ();
                var token = disp.Token;

                Task.Factory.StartNew (() => {
                    using (var source = CGImageSource.FromUrl (url)) {
                        if (source.Handle == IntPtr.Zero)
                            throw new Exception (string.Format ("Could not create source for '{0}'", url));

                        var sourceSize = ImageHelper.Measure (source);
                        int maxPixelSize = GetMaxPixelSize (sourceSize, description.Size);

                        using (var scaled = CreateThumbnail (source, maxPixelSize, token))
                        using (var cropped = ScaleAndCrop (scaled, description.Size, description.Mode, token))
                            SaveToRequest (cropped, source.TypeIdentifier, request);

                        o.OnCompleted ();
                    }
                }, token).RouteExceptions (o);

                return disp;
            });
        }
Beispiel #11
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            addButton = new UIBarButtonItem(UIBarButtonSystemItem.Add, (s,e) =>{
                var filename = DateTime.Now.ToString ("yyyyMMdd_HHmmss") + ".task";
                if (AppDelegate.HasiCloud) {
                    var p1 = Path.Combine(AppDelegate.iCloudUrl.Path, "Documents");
                    var p2 = Path.Combine (p1, filename);
                    var ubiq = new NSUrl(p2, false);

                    var task = new TaskDocument(ubiq);
                    task.Save (task.FileUrl, UIDocumentSaveOperation.ForCreating
                    , (success) => {
                        Console.WriteLine ("Save completion:"+ success);
                        tasks.Add (task);
                        Reload();
                    });
                }
            });
            NavigationItem.RightBarButtonItem = addButton;

            // UIBarButtonSystemItem.Refresh or http://barrow.io/posts/iphone-emoji/
            refreshButton = new UIBarButtonItem('\uE049'.ToString ()
            , UIBarButtonItemStyle.Plain
            , (s,e) => {
                LoadTasks(null);
            });

            NavigationItem.LeftBarButtonItem = refreshButton;
            LoadTasks(null);
        }
		protected override void OnElementChanged (ElementChangedEventArgs<View> e)
		{
			base.OnElementChanged (e);

			//Get the video
			//bubble up to the AVPlayerLayer
			var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp");
			_asset = AVAsset.FromUrl (url);

			_playerItem = new AVPlayerItem (_asset);

			_player = new AVPlayer (_playerItem);

			_playerLayer = AVPlayerLayer.FromPlayer (_player);

			//Create the play button
			playButton = new UIButton ();
			playButton.SetTitle ("Play Video", UIControlState.Normal);
			playButton.BackgroundColor = UIColor.Gray;

			//Set the trigger on the play button to play the video
			playButton.TouchUpInside += (object sender, EventArgs arg) => {
				_player.Play();
			};
		}
        public void AddBarButtonText(object sender, EventArgs e)
        {
            var nativeTextField = Control as UITextField;

            NSUrl url = new NSUrl ("tel:" + nativeTextField.Text);
            UIApplication.SharedApplication.OpenUrl (url);
        }
		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);
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            if ( UIDevice.CurrentDevice.CheckSystemVersion(7, 0) )
            {
                EdgesForExtendedLayout = UIRectEdge.None;
            }

            if (WTArchitectView.IsDeviceSupportedForAugmentedRealityMode (WTAugmentedRealityMode._Geo))
            {
                arView = new WTArchitectView (UIScreen.MainScreen.Bounds, null, WTAugmentedRealityMode._Geo);
                arView.SetLicenseKey ("Ug7LmdNQJKN5AX85OMRGt1LIk1xBmwOWi8u+4eEVBpIvKZ8EWh2w1z3f5Cd4YHnWlEIdazY1envd/W7Xy5U4GUlkNmH2l9ddWZr5gIsz0zuD4GZVunmt0o49f4rDv+ssM78CAklidZeMkxqTGGoG6I8UjoegiWEKtzoH3qWpruNTYWx0ZWRfX3mWnNyLFq5Z+rfkc+m7sBeEhO/Urh2wYX/E57J6MdWPrCvmW0Zrt0RfAkUjmmHZ9MdjOyghN4VtSnY6nwc+Xz2Wg8vrCG02TIMw8SbNBRqP4ljrg3BnmjSONHRC69rzLnzCalB+YXAIdh5QdZI8TG8nJNUQCZGmjdrF5SpznSbcLpjDqfI36NaGW3cnH6evloXrcItbrnJDeeZlfB7CZj6PpLaf6q4GpKJRIEiVbeY3UpQ19+5IsydEbo0eVwZQFtE/G/NB7mNM1SjwteJ53EumNT9hd/4fMmk7L3nUj4kpyZ2gttPTS0/1kxtwVJjfRntngMiSN6czJrmrI5IyqN3qjEDextUNJ6zpvj97Vx/k+6RkItCgbMLZzdGgnyvIq9jumKiICOZXcFz4iacFFsYag4w87FoUwJFdp2SAsuW374FdmMB2tE5Zk5CONbQvMCKkMwdT6RnqA0SrzX4NA9qDLv8DwcoOu3jiszRE//8uOGS26I4NIznQniu8gn04sdeDm3P50rVkB7Vq3CDP89LIE8CoqChJ9DVEm2IzwfHFRd6cDalxC9szRKxOI4H5Z6wJY4tPHTeQha3Gp4jFQXLbtwfPLPcr+DyH8GkOf6+aIbzz3AVZZz9v67JN2W5O1xR2BZXAjkE0SC4zXK2g0H6MuDEYLdLHZCnl8ik/Aw3ydyFe5zw9+olNC/72uH5rA5ZLyiACVauyXwwsc6bNzJu3c5Dyb724zg==");

                var absoluteWorldUrl = WorldOrUrl;
                if (!IsUrl)
                    absoluteWorldUrl = NSBundle.MainBundle.BundleUrl.AbsoluteString + "ARchitectExamples/" + WorldOrUrl + "/index.html";
                Console.WriteLine (absoluteWorldUrl);
                var u = new NSUrl (absoluteWorldUrl);
                arView.LoadArchitectWorldFromUrl (u);

                View.AddSubview (arView);
            }
            else
            {
                var adErr = new UIAlertView ("Unsupported Device", "This device is not capable of running ARchitect Worlds. Requirements are: iOS 5 or higher, iPhone 3GS or higher, iPad 2 or higher. Note: iPod Touch 4th and 5th generation are only supported in WTARMode_IR.", null, "OK", null);
                adErr.Show ();
            }
        }
Beispiel #16
0
		public PdfViewController (NSUrl url) : base()
		{
			Url = url;
			View = new UIView ();
			View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
			View.AutosizesSubviews = true;
			
			PdfDocument = CGPDFDocument.FromUrl (Url.ToString ());
			
			// For demo purposes, show first page only.
			PdfPage = PdfDocument.GetPage (1);
			PdfPageRect = PdfPage.GetBoxRect (CGPDFBox.Crop);
			
			// Setup tiled layer.
			TiledLayer = new CATiledLayer ();
			TiledLayer.Delegate = new TiledLayerDelegate (this);
			TiledLayer.TileSize = new SizeF (1024f, 1024f);
			TiledLayer.LevelsOfDetail = 5;
			TiledLayer.LevelsOfDetailBias = 5;
			TiledLayer.Frame = PdfPageRect;
			
			ContentView = new UIView (PdfPageRect);
			ContentView.Layer.AddSublayer (TiledLayer);
			
			// Prepare scroll view.
			ScrollView = new UIScrollView (View.Frame);
			ScrollView.AutoresizingMask = View.AutoresizingMask;
			ScrollView.Delegate = new ScrollViewDelegate (this);
			ScrollView.ContentSize = PdfPageRect.Size;
			ScrollView.MaximumZoomScale = 10f;
			ScrollView.MinimumZoomScale = 1f;
			ScrollView.ScrollEnabled = true;
			ScrollView.AddSubview (ContentView);
			View.AddSubview (ScrollView);
		}
Beispiel #17
0
		public override bool HandleOpenURL(UIApplication application, NSUrl url)
		{
			if (url == null)
				return false;
			var uri = new System.Uri(url.ToString());

//			if (Slideout != null)
//			{
//				if (!string.IsNullOrEmpty(uri.Host))
//				{
//					string username = uri.Host;
//					string repo = null;
//
//					if (uri.Segments.Length > 1)
//						repo = uri.Segments[1].Replace("/", "");
//
//					if (repo == null)
//						Slideout.SelectView(new CodeBucket.ViewControllers.ProfileViewController(username));
//					else
//						Slideout.SelectView(new CodeBucket.ViewControllers.RepositoryInfoViewController(username, repo, repo));
//				}
//			}

			return true;
		}
        public static BaseItemView Create (CGRect frame, NodeViewController nodeViewController, TreeNode node, string filePath, UIColor kleur)
        {
            var view = BaseItemView.Create(frame, nodeViewController, node, kleur);
            UIWebView webView = new UIWebView();

			string extension = Path.GetExtension (filePath);
			if (extension == ".odt") {
				string viewerPath = NSBundle.MainBundle.PathForResource ("over/viewer/index", "html");

				Uri fromUri = new Uri(viewerPath);
				Uri toUri = new Uri(filePath);
				Uri relativeUri = fromUri.MakeRelativeUri(toUri);
				String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

				NSUrl finalUrl = new NSUrl ("#" + relativePath.Replace(" ", "%20"), new NSUrl(viewerPath, false));
				webView.LoadRequest(new NSUrlRequest(finalUrl));
				webView.ScalesPageToFit = true;
				view.ContentView = webView;

				return view;
			} else {
				NSUrl finalUrl = new NSUrl (filePath, false);
				webView.LoadRequest(new NSUrlRequest(finalUrl));
				webView.ScalesPageToFit = true;
				view.ContentView = webView;

				return view;
			}
		
        }
		public override void LoadHtmlString (string s, NSUrl baseUrl) 
		{
			if (baseUrl == null) {
				baseUrl = new NSUrl (NSBundle.MainBundle.BundlePath, true);
			}
			base.LoadHtmlString (s, baseUrl);
		}
		public override void StartProvidingItemAtUrl (NSUrl url, Action<NSError> completionHandler)
		{
			Console.WriteLine ("FileProvider StartProvidingItemAtUrl");

			// When this method is called, your extension should begin to download,
			// create, or otherwise make a local file ready for use.
			// As soon as the file is available, call the provided completion handler.
			// If any errors occur during this process, pass the error to the completion handler.
			// The system then passes the error back to the original coordinated read.

			NSError error, fileError = null;

			string str = "These are the contents of the file";
			NSData fileData = ((NSString)str).Encode (NSStringEncoding.UTF8);

			Console.WriteLine ("FileProvider before CoordinateWrite url {0}", url);
			FileCoordinator.CoordinateWrite (url, 0, out error, (newUrl) => {
				Console.WriteLine ("before data save");
				fileData.Save (newUrl, 0, out fileError);
				Console.WriteLine ("data saved");
			});
			Console.WriteLine ("FileProvider after CoordinateWrite");
			Console.WriteLine ("FileProvider CoordinateWrite error {0}", error);

			completionHandler (error ?? fileError);
		}
Beispiel #21
0
 public CGDataConsumer(NSUrl url)
 {
     // not it's a __nullable parameter but it would return nil (see unit tests) and create an invalid instance
     if (url == null)
         throw new ArgumentNullException ("url");
     handle = CGDataConsumerCreateWithURL (url.Handle);
 }
        public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
        {
            ShopsTableCell cell = new ShopsTableCell(cellIdentifier);
            try
            {
                cell = tableView.DequeueReusableCell(cellIdentifier) as ShopsTableCell;

                if (cell == null)
                    cell = new ShopsTableCell(cellIdentifier);
                if (!String.IsNullOrEmpty(tableItems[indexPath.Row].FirstPhotoUrl))
                {
                    NSUrl nsUrl = new NSUrl(tableItems[indexPath.Row].FirstPhotoUrl);
                    NSData data = NSData.FromUrl(nsUrl);

                    if (data != null)
                        cell.UpdateCell(tableItems[indexPath.Row].Name, tableItems[indexPath.Row].Description, tableItems[indexPath.Row].Price.ToString("N2"), new UIImage(data));
                    else
                        cell.UpdateCell(tableItems[indexPath.Row].Name, tableItems[indexPath.Row].Description, tableItems[indexPath.Row].Price.ToString("N2"), new UIImage());
                }
                else
                    cell.UpdateCell(tableItems[indexPath.Row].Name, tableItems[indexPath.Row].Description, tableItems[indexPath.Row].Price.ToString("N2"), new UIImage());

                OnGotCell();
                CellOn = indexPath.Row;
            }
            catch (Exception exception)
            {
                ErrorHandler.Save(exception, MobileTypeEnum.iPhone);
            }
            return cell;
        }
		// TODO - add reachability check
		public static async Task<ImageDownloadResult> DownloadImage(string url)
		{
			ImageDownloadResult result = null;

			await Task.Run(() =>
			{
				try
				{
					using (var downloadUrl = new NSUrl(url))
					{
						using (var imageData = NSData.FromUrl(downloadUrl))
						{
							var image = UIImage.LoadFromData(imageData);
							result = new ImageDownloadResult(image);
						}
					}		
				}
				catch (Exception e)
				{
					Debug.WriteLine("Exception when downloding file: " + url + " - exception: " + e);
					result = new ImageDownloadResult(ServiceAccessError.ErrorUnknown);
				}
			});

			return result;
		}
Beispiel #24
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.
			string translatedNumber = "";

			translateBtn.TouchUpInside += (object sender, EventArgs e) => {
				translatedNumber = PhoneTranslator.ToNumber(phoneNumberText.Text);

				phoneNumberText.ResignFirstResponder();

				if(translatedNumber == "")
				{
					callBtn.SetTitle("Call", UIControlState.Normal);
					callBtn.Enabled = false;
				}
				else
				{
					callBtn.SetTitle("Call " + translatedNumber, UIControlState.Normal);
					callBtn.Enabled = true;
				}
			};

			callBtn.TouchUpInside += (object sender, EventArgs e) => {
				var url = new NSUrl("tel:" + translatedNumber);

				if(!UIApplication.SharedApplication.OpenUrl(url))
				{
					var alert = UIAlertController.Create("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
					alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
					PresentViewController(alert, true, null);
				}
			};
		}
Beispiel #25
0
 public SKVideoNode(NSUrl url)
 {
     if (CheckSystemVersion ())
         Handle = InitWithURL (url);
     else
         Handle = InitWithVideoURL (url);
 }
Beispiel #26
0
 // Apple deprecated videoNodeWithVideoURL: in 10.10/8.0
 // and made available videoNodeWithURL: so we invoke
 // the right one at runtime depending on which OS version we are running
 // https://bugzilla.xamarin.com/show_bug.cgi?id=37727
 public static SKVideoNode FromUrl(NSUrl videoUrl)
 {
     if (CheckSystemVersion ())
         return VideoNodeWithURL (videoUrl);
     else
         return VideoNodeWithVideoURL (videoUrl);
 }
Beispiel #27
0
        public void BindToView()
        {
            ExibitInfo info = _controller.GetExibitInfo();

            NSUrl dirUrl = new NSUrl(info.DirPath, true);
            _contentDisplayer.LoadHtmlString(info.HtmlExibitInfo, dirUrl);
        }
Beispiel #28
0
        public static UIImage FromUrl(string uri)
        {
            var imageName = uri.Substring(uri.LastIndexOf ('/') + 1);

            if (File.Exists (Path.Combine (NativeImagesPath, imageName)))
                return UIImage.FromFile (Path.Combine (NativeImagesPath, imageName));

            if (File.Exists (Path.Combine (ImagesCachePath, imageName)))
                return UIImage.FromFile (Path.Combine (ImagesCachePath, imageName));

            if (Items.ContainsKey (uri))
                return Items [uri];

            using (var url = new NSUrl (uri))
            using (var data = NSData.FromUrl (url)) {
                var image = UIImage.LoadFromData (data);

                if (!NSFileManager.DefaultManager.FileExists (ImagesCachePath))
                    NSFileManager.DefaultManager.CreateDirectory (ImagesCachePath, false, null);

                var result = NSFileManager.DefaultManager.CreateFile (Path.Combine (ImagesCachePath, imageName), data, new NSFileAttributes ());
                if (!result)
                    Items [uri] = image;

                return image;
            }
        }
 public void Donate()
 {
     using (NSUrl url = new NSUrl(_paypalUrl))
     {
         UIApplication.SharedApplication.OpenUrl(url);
     }
 }
Beispiel #30
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            //largely taken from the xamarin website videoplayer tutorial

            //build the path to the location where the movie was saved
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var library = System.IO.Path.Combine (documents, "..", "Library");
            var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov");

            NSUrl url = new NSUrl (urlpath, false);

            _asset = AVAsset.FromUrl(url);
            _playerItem = new AVPlayerItem (_asset);
            _player = new AVPlayer (_playerItem);

            _playerLayer = AVPlayerLayer.FromPlayer (_player);
            _playerLayer.Frame = View.Frame;
            View.Layer.AddSublayer (_playerLayer);

            //this code makes UI controls sit on top of the movie layer.  Allows you to just place the controls in interface builder
            UIView cameraView = new UIView ();
            this.View.AddSubview (cameraView);
            this.View.SendSubviewToBack (cameraView);
            cameraView.Layer.AddSublayer (_playerLayer);

            _player.Play ();

            this.btnDonePlaying.TouchUpInside += stopPlaying;
        }
        private void HandlePersistableContentKeyRequest(AVPersistableContentKeyRequest keyRequest)
        {
            /*
             * The key ID is the URI from the EXT-X-KEY tag in the playlist (e.g. "skd://key65") and the
             * asset ID in this case is "key65".
             */

            var contentKeyIdentifierString = keyRequest.Identifier as NSString;

            if (contentKeyIdentifierString == null)
            {
                Debug.WriteLine("Failed to retrieve the assetID from the keyRequest!");
                return;
            }

            var contentKeyIdentifierUrl = new NSUrl(contentKeyIdentifierString);
            var assetIdString           = contentKeyIdentifierUrl.Host;
            var assetIdData             = NSData.FromString(assetIdString, NSStringEncoding.UTF8);

            Action <NSData, NSError> completionHandler = async(data, error) =>
            {
                if (error != null)
                {
                    keyRequest.Process(error);
                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                    return;
                }

                if (data == null)
                {
                    return;
                }

                try
                {
                    var ckcData = await RequestContentKeyFromKeySecurityModule(data, assetIdString);

                    NSData persistentKey = keyRequest.GetPersistableContentKey(ckcData, null, out error);

                    WritePersistableContentKey(persistentKey, new NSString(assetIdString));

                    /*
                     * AVContentKeyResponse is used to represent the data returned from the key server when requesting a key for
                     * decrypting content.
                     */
                    var keyResponse = AVContentKeyResponse.Create(persistentKey);

                    /*
                     * Provide the content key response to make protected content available for processing.
                     */
                    keyRequest.Process(keyResponse);

                    string assetName    = string.Empty;
                    bool   assetRemoved = false;

                    if (contentKeyToStreamNameMap.TryGetValue(assetIdString, out assetName))
                    {
                        assetRemoved = contentKeyToStreamNameMap.Remove(assetIdString);
                    }

                    if (!string.IsNullOrWhiteSpace(assetName) && assetRemoved && !contentKeyToStreamNameMap.ContainsKey(assetIdString))
                    {
                        var userInfo = new Dictionary <string, object>();
                        userInfo["name"] = assetName;

                        var userInfoDictionary = NSDictionary.FromObjectsAndKeys(userInfo.Values.ToArray(), userInfo.Keys.ToArray());
                        NSNotificationCenter.DefaultCenter.PostNotificationName(ContentKeyDelegate.DidSaveAllPersistableContentKey, null, userInfoDictionary);
                    }

                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                }
                catch (Exception ex)
                {
                    pendingPersistableContentKeyIdentifiers.Remove(assetIdString);
                    Debug.WriteLine(ex.Message);
                }
            };

            try
            {
                var applicationCertificate = RequestApplicationCertificate();

                var keys    = new[] { new NSString(AVContentKeyRequest.ProtocolVersions) };
                var numbers = new NSMutableArray <NSNumber>();
                numbers.Add(new NSNumber(1));
                var objects = new NSObject[] { numbers };
                var options = new NSDictionary <NSString, NSObject>(keys, objects);

                if (PersistableContentKeyExistsOnDisk(assetIdString))
                {
                    var urlToPersistableKey = CreateUrlForPersistableContentKey(assetIdString);
                    var contentKey          = NSFileManager.DefaultManager.Contents(urlToPersistableKey.Path);

                    if (contentKey == null)
                    {
                        pendingPersistableContentKeyIdentifiers.Remove(assetIdString);

                        /*
                         * Key requests should never be left dangling.
                         * Attempt to create a new persistable key.
                         */
                        keyRequest.MakeStreamingContentKeyRequestData(applicationCertificate, assetIdData, options, completionHandler);

                        return;
                    }

                    /*
                     * Create an AVContentKeyResponse from the persistent key data to use for requesting a key for
                     * decrypting content.
                     */

                    var keyResponse = AVContentKeyResponse.Create(contentKey);
                    keyRequest.Process(keyResponse);

                    return;
                }

                keyRequest.MakeStreamingContentKeyRequestData(applicationCertificate, assetIdData, options, completionHandler);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failure responding to an AVPersistableContentKeyRequest when attemping to determine if key is already available for use on disk. {ex.Message}");
            }
        }
Beispiel #32
0
        static FileResult DictionaryToMediaFile(NSDictionary info)
        {
            if (info == null)
            {
                return(null);
            }

            PHAsset phAsset  = null;
            NSUrl   assetUrl = null;

            if (Platform.HasOSVersion(11, 0))
            {
                assetUrl = info[UIImagePickerController.ImageUrl] as NSUrl;

                // Try the MediaURL sometimes used for videos
                if (assetUrl == null)
                {
                    assetUrl = info[UIImagePickerController.MediaURL] as NSUrl;
                }

                if (assetUrl != null)
                {
                    if (!assetUrl.Scheme.Equals("assets-library", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(new UIDocumentFileResult(assetUrl));
                    }

                    phAsset = info.ValueForKey(UIImagePickerController.PHAsset) as PHAsset;
                }
            }

            if (phAsset == null)
            {
                assetUrl = info[UIImagePickerController.ReferenceUrl] as NSUrl;

                if (assetUrl != null)
                {
                    phAsset = PHAsset.FetchAssets(new NSUrl[] { assetUrl }, null)?.LastObject as PHAsset;
                }
            }

            if (phAsset == null || assetUrl == null)
            {
                var img = info.ValueForKey(UIImagePickerController.OriginalImage) as UIImage;

                if (img != null)
                {
                    return(new UIImageFileResult(img));
                }
            }

            if (phAsset == null || assetUrl == null)
            {
                return(null);
            }

            string originalFilename;

            if (Platform.HasOSVersion(9, 0))
            {
                originalFilename = PHAssetResource.GetAssetResources(phAsset).FirstOrDefault()?.OriginalFilename;
            }
            else
            {
                originalFilename = phAsset.ValueForKey(new NSString("filename")) as NSString;
            }

            return(new PHAssetFileResult(assetUrl, phAsset, originalFilename));
        }
Beispiel #33
0
        public Task PlatformComposeAsync(EmailMessage?message)
        {
            var isComposeSupported = InvokeOnMainThread(() => NSWorkspace.SharedWorkspace.UrlForApplication(NSUrl.FromString("mailto:")) != null);

            if (!isComposeSupported)
            {
                throw new FeatureNotSupportedException();
            }

            var url = Email2.GetMailToUri(message);

            using var nsurl = NSUrl.FromString(url);
            NSWorkspace.SharedWorkspace.OpenUrl(nsurl);
            return(Task.CompletedTask);
        }
Beispiel #34
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Устанавливаем бэкграунд из текстуры
            UIImageView background = new UIImageView(
                ResizeUIImage(
                    UIImage.FromFile("background.jpg"), (float)View.Bounds.Size.Width, (float)View.Bounds.Size.Height));

            View.Add(background);

            UILabel gameOverLabel = new UILabel
            {
                Frame         = new CoreGraphics.CGRect(View.Bounds.Size.Width / 2 - 75, 150, 150, 50),
                Font          = CommonFont,
                TextAlignment = UITextAlignment.Center,
                TextColor     = UIColor.White
            };

            gameOverLabel.Text = "Игра окончена!";
            View.Add(gameOverLabel);

            UILabel scoreTitle = new UILabel
            {
                Frame         = new CoreGraphics.CGRect(View.Bounds.Size.Width / 2 - 75, 170, 150, 50),
                Font          = CommonFont,
                TextAlignment = UITextAlignment.Center,
                TextColor     = UIColor.White
            };

            scoreTitle.Text = "Ваш счёт:";
            View.Add(scoreTitle);

            score.Frame         = new CoreGraphics.CGRect(View.Bounds.Size.Width / 2 - 75, 185, 150, 50);
            score.TextAlignment = UITextAlignment.Center;
            score.Font          = UIFont.FromName("GillSans-BoldItalic", 18f);
            score.TextColor     = UIColor.White;
            View.Add(score);

            UIButton startButton = new UIButton
            {
                Frame           = new CoreGraphics.CGRect(View.Bounds.Size.Width / 2 - 75, View.Bounds.Size.Height - 100, 150, 50),
                Font            = CommonFont,
                BackgroundColor = ButtonColor
            };

            startButton.SetTitle("В МЕНЮ", UIControlState.Normal);

            View.Add(startButton);

            startButton.TouchUpInside += (sender, e) =>
            {
                UIViewController mainMenu = Storyboard.InstantiateViewController("MainMenu");
                NavigationController.PushViewController(mainMenu, true);
            };

            NSUrl url;

            if (int.Parse(score.Text) >= 3500)
            {
                url = NSUrl.FromFilename("greatScoreRus.wav");
            }
            else if (int.Parse(score.Text) >= 2000 && int.Parse(score.Text) < 3500)
            {
                url = NSUrl.FromFilename("loserScoreRus.wav");
            }
            else if (int.Parse(score.Text) >= 500 && int.Parse(score.Text) < 2000)
            {
                url = NSUrl.FromFilename("antScoreRus.wav");
            }
            else
            {
                url = NSUrl.FromFilename("veryLowScoreRus.wav");
            }

            SystemSound ss = new SystemSound(url);

            ss.PlayAlertSound();
        }
Beispiel #35
0
 public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
 {
     AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(url);
     return(true);
 }
        static NSArray CopyProxiesForAutoConfigurationScript(NSString proxyAutoConfigurationScript, NSUrl targetURL)
        {
            IntPtr err;
            IntPtr native = CFNetworkCopyProxiesForAutoConfigurationScript(proxyAutoConfigurationScript.Handle, targetURL.Handle, out err);

            return(native == IntPtr.Zero ? null : new NSArray(native));
        }
Beispiel #37
0
 public override void SendAsync(NSUrl url, NSString method, NSDictionary <NSString, NSString> headers, NSData data, NSArray retryIntervals, bool compressionEnabled, MSHttpRequestCompletionHandler completionHandler)
 {
     SendAsync(url, method, headers, data, completionHandler);
 }
 public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
 {
     return(((FlexViewViewController)Window.RootViewController).Open(url));
 }
Beispiel #39
0
 public UIViewController GetViewControllerForItem(NSUrl atUri, NSData data, NSFileAttributes fileAttribute)
 {
     return(new WebViewController(atUri));
 }
Beispiel #40
0
 private void handleCallback(NSUrl url)
 {
     Console.WriteLine("Appended url: " + url.ToString());
 }
Beispiel #41
0
 public void LoadHtmlString(string htmlString, NSUrl baseUrl)
 {
     LoadHtmlString((NSString)htmlString, baseUrl);
 }
Beispiel #42
0
 public AVAudioPlayer(NSUrl url, NSError error) : this(url, IntPtr.Zero)
 {
 }
Beispiel #43
0
        public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            ActivityMediator.Instance.Send(url.AbsoluteString);

            return(true);
        }
 public AVAudioRecorder(NSUrl url, NSDictionary settings, NSError outError)
 {
     throw new Exception("This constructor is no longer supported, use the AVAudioRecorder.ToUrl factory method instead");
 }
 internal FileBase(NSUrl file)
     : this(NSFileManager.DefaultManager.DisplayName(file?.Path))
 {
 }
 public static void SetBrokerResponse(NSUrl brokerResponse)
 {
     BrokerHelper.brokerResponse = brokerResponse;
     brokerResponseReady.Release();
 }
 public override void DidPickDocument(UIDocumentPickerViewController controller, NSUrl url)
 {
     _deviceActionService.PickedDocument(url);
 }
Beispiel #48
0
        public byte[] GetVideoThumbnailFromFile(string path)
        {
            var asset = AVAsset.FromUrl(NSUrl.FromFilename(path));

            return(GetImageSource(asset));
        }
Beispiel #49
0
        //sharing options
        private void shareAlert(string title, string message)
        {
            UIAlertController shareController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);


            //facebook servers
            UIAlertAction facebookAction = UIAlertAction.Create("Facebook", UIAlertActionStyle.Default, (Action) => {
                NSUrl facebookURL = NSUrl.FromString("");

                if (UIApplication.SharedApplication.CanOpenUrl(facebookURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(facebookURL);
                    shareController.Dispose();
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(facebookURL) == false)
                {
                    AI.AIEnglish("Cannot connect you to the facebook servers. Check your internet connection", "en-US", 2.0f, 1.0f, 1.0f);
                    shareController.Dispose();
                }
            });

            //twitter servers
            UIAlertAction twitterAction = UIAlertAction.Create("Twitter", UIAlertActionStyle.Default, (Action) =>
            {
                NSUrl twitterURL = NSUrl.FromString("");

                if (UIApplication.SharedApplication.CanOpenUrl(twitterURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(twitterURL);
                    shareController.Dispose();
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(twitterURL) == false)
                {
                    AI.AIEnglish("Cannot connect you to the twitter servers. Check your internet connection", "en-US", 2.0f, 1.0f, 1.0f);
                    shareController.Dispose();
                }
            });

            //email a friend option
            UIAlertAction emailFriend = UIAlertAction.Create("\ud83d\udc8c Email a Friend", UIAlertActionStyle.Default, (Action) =>
            {
                MFMailComposeViewController mailEmail = new MessageUI.MFMailComposeViewController();

                if (MFMailComposeViewController.CanSendMail == true)
                {
                    this.PresentViewController(mailEmail, true, null);
                }

                else
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("Error cannot open mail box. Check if the mail box is enabled on your iPad", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("Error cannot open mail box. Check if the mail box is enabled on your iPhone", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                }

                mailEmail.Finished += (sender, e) =>
                {
                    //mail closes
                    mailEmail.DismissViewController(true, null);
                };
            });

            //text a friend option
            UIAlertAction textFriend = UIAlertAction.Create("\ud83d\udcf2 Text a friend", UIAlertActionStyle.Default, (Action) => {
                NSUrl textFriendURL = NSUrl.FromString("sms:");

                if (UIApplication.SharedApplication.CanOpenUrl(textFriendURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(textFriendURL);
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(textFriendURL) == false)
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("Error cannot open text message box. Check if the text messages are enabled on your iPad", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("Error cannot open text message box. Check if the text messages are enabled on your iPhone", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                }
            });

            UIAlertAction rateOnAppStore = UIAlertAction.Create("\ud83d\udc4d Rate on App Store", UIAlertActionStyle.Default, (Action) =>
            {
                NSUrl urlRateAppURL = NSUrl.FromString("");                 //url of application on app store

                if (UIApplication.SharedApplication.CanOpenUrl(urlRateAppURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(urlRateAppURL);
                }

                else
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("No internet connection detected. Cannot connect to the App Store", "en-US", 2.5f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("No internet connection detected.  Cannot connect to the App Store", "en-US", 2.5f, 1.0f, 1.0f);
                    }
                    shareController.Dispose();
                }
            });

            UIAlertAction denied = UIAlertAction.Create("Maybe Later", UIAlertActionStyle.Destructive, (Action) =>
            {
                shareController.Dispose();
            });

            shareController.AddAction(facebookAction);
            shareController.AddAction(twitterAction);
            shareController.AddAction(emailFriend);
            shareController.AddAction(textFriend);
            shareController.AddAction(rateOnAppStore);
            shareController.AddAction(denied);

            if (this.PresentedViewController == null)
            {
                this.PresentViewController(shareController, true, null);
            }

            else if (this.PresentedViewController != null)
            {
                this.PresentedViewController.DismissViewController(true, () =>
                {
                    this.PresentedViewController.Dispose();
                    this.PresentViewController(shareController, true, null);
                });
            }
        }
Beispiel #50
0
 public StretchImage(NSUrl url) : base(url)
 {
     Initialize();
 }
 /// <summary>
 /// Loads from URL.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <returns>UIImage.</returns>
 public static UIImage LoadFromUrl(string uri)
 {
     using (var url = new NSUrl(uri)) using (var data = NSData.FromUrl(url)) return(UIImage.LoadFromData(data));
 }
        public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        {
            Task.Run(async() =>
            {
                if ("Inbox".Equals(Path.GetFileName(Path.GetDirectoryName(url.Path))))
                {
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile f          = await FileSystem.Current.GetFileFromPathAsync(url.Path);
                    await f.MoveAsync(Path.Combine(incoming.Path, f.Name), NameCollisionOption.GenerateUniqueName);
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
                else if (url.Path?.EndsWith(".cb5") ?? false)
                {
                    url.StartAccessingSecurityScopedResource();
                    try {
                        //using (MemoryStream s = new MemoryStream()) {
                        //    NSInputStream stream = NSInputStream.FromUrl(url);
                        //    byte[] buffer = new byte[1024];
                        //    while (stream.HasBytesAvailable()) {
                        //        int read = (int)stream.Read(buffer, 1024);
                        //        s.Write(buffer, 0, read);
                        //    }
                        //    s.Seek(0, SeekOrigin.Begin);
                        //NSFileHandle fs = NSFileHandle.OpenReadUrl(url, out NSError err);
                        //NSData data = fs.ReadDataToEndOfFile();
                        //fs.CloseFile();
                        //using (Stream f = data.AsStream()) {AsStream
                        //new MyInputStream(NSInputStream.FromUrl(url))) {
                        //NSData d = await url.LoadDataAsync("text/xml");
                        //File.OpenRead(url.Path)
                        using (Stream s = File.OpenRead(url.Path)) {
                            Player player          = Player.Serializer.Deserialize(s) as Player;
                            BuilderContext Context = new BuilderContext(player);
                            PluginManager manager  = new PluginManager();
                            manager.Add(new SpellPoints());
                            manager.Add(new SingleLanguage());
                            manager.Add(new CustomBackground());
                            manager.Add(new NoFreeEquipment());
                            Context.Plugins = manager;


                            Context.UndoBuffer     = new LinkedList <Player>();
                            Context.RedoBuffer     = new LinkedList <Player>();
                            Context.UnsavedChanges = 0;

                            Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                            {
                                LoadingProgress loader   = new LoadingProgress(Context);
                                LoadingPage l            = new LoadingPage(loader, false);
                                App.MainTab.SelectedItem = App.MainTab.Children[1];
                                await App.MainTab.Children[2].Navigation.PushModalAsync(l);
                                var t = l.Cancel.Token;
                                try
                                {
                                    await loader.Load(t).ConfigureAwait(false);
                                    t.ThrowIfCancellationRequested();
                                    PlayerBuildModel model = new PlayerBuildModel(Context);
                                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                                    {
                                        await App.MainTab.Children[1].Navigation.PopModalAsync(false);
                                        await App.MainTab.Children[1].Navigation.PushModalAsync(new NavigationPage(new FlowPage(model)));
                                    });
                                } catch (Exception e) {
                                    ConfigManager.LogError(e);
                                }
                            });
                        }
                        url.StopAccessingSecurityScopedResource();
                    }
                    catch (Exception e)
                    {
                        ConfigManager.LogError(e);
                    }
                }
                else if (url.Path.StartsWith(App.Storage.Path, System.StringComparison.Ordinal))
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(await FileSystem.Current.GetFolderFromPathAsync(Path.GetDirectoryName(url.Path))));
                    });
                }
                else
                {
                    url.StartAccessingSecurityScopedResource();
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile target     = await incoming.CreateFileAsync(url.LastPathComponent, CreationCollisionOption.GenerateUniqueName);
                    using (Stream f = File.OpenRead(url.Path))
                    {
                        using (Stream o = await target.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
                        {
                            await f.CopyToAsync(o);
                        }
                    }
                    url.StopAccessingSecurityScopedResource();
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
            }).Forget();
            return(true);
        }
        static NSArray CopyProxiesForURL(NSUrl url, NSDictionary proxySettings)
        {
            IntPtr native = CFNetworkCopyProxiesForURL(url.Handle, proxySettings.Handle);

            return(native == IntPtr.Zero ? null : new NSArray(native));
        }
        public static CFRunLoopSource ExecuteProxyAutoConfigurationURL(NSUrl proxyAutoConfigurationURL, NSUrl targetURL, CFProxyAutoConfigurationResultCallback resultCallback, CFStreamClientContext clientContext)
        {
            if (proxyAutoConfigurationURL == null)
            {
                throw new ArgumentNullException("proxyAutoConfigurationURL");
            }

            if (targetURL == null)
            {
                throw new ArgumentNullException("targetURL");
            }

            if (resultCallback == null)
            {
                throw new ArgumentNullException("resultCallback");
            }

            if (clientContext == null)
            {
                throw new ArgumentNullException("clientContext");
            }

            IntPtr source = CFNetworkExecuteProxyAutoConfigurationURL(proxyAutoConfigurationURL.Handle, targetURL.Handle, resultCallback, clientContext);

            return((source == IntPtr.Zero) ? null : new CFRunLoopSource(source));
        }
Beispiel #55
0
        // PrepareForSegue is only used when a Segue is created in the storyboard
        // our final implementation handles this transition in code when
        // CallHistoryButton is pressed

//		public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
//		{
//			base.PrepareForSegue (segue, sender);
//
//			// set the View Controller that’s powering the screen we’re
//			// transitioning to
//
//			var callHistoryContoller = segue.DestinationViewController as CallHistoryController;
//
//			//set the Table View Controller’s list of phone numbers to the
//			// list of dialed phone numbers
//
//			if (callHistoryContoller != null) {
//				callHistoryContoller.PhoneNumbers = PhoneNumbers;
//			}
//		}

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.

            // Start with the CallButton Disabled
            CallButton.Enabled = false;

            // Code for when TranslateButton is pressed
            TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
                // Convert the phone number with text to a number
                // using PhoneTranslator.cs
                translatedNumber = Core.PhonewordTranslator.ToNumber(
                    PhoneNumberText.Text);

                // Dismiss the keyboard if text field was tapped
                PhoneNumberText.ResignFirstResponder();


                if (translatedNumber == "")
                {
                    // If the Translate Button was pressed with no input entered, set the Call Button
                    // to its original state
                    CallButton.SetTitle("Call", UIControlState.Normal);
                    CallButton.Enabled = false;
                }
                else
                {
                    // If the Translate Button was pressed with an input, add the translated number
                    // to the Call Button title and enable the Button to be pressed.
                    CallButton.SetTitle("Call " + translatedNumber, UIControlState.Normal);
                    CallButton.Enabled = true;
                }
            };

            // Code for when CallHistoryButton is pressed
            CallHistoryButton.TouchUpInside += (object sender, EventArgs e) => {
                // Launches a new instance of CallHistoryController
                CallHistoryController callHistory = this.Storyboard.InstantiateViewController("CallHistoryController") as CallHistoryController;
                if (callHistory != null)
                {
                    // Set the PhoneNumbers List in the CallHistoryController to the PhoneNumbersList in this View Controller
                    callHistory.PhoneNumbers = PhoneNumbers;
                    // Push the callHistoryController onto the NavigationController's stack
                    this.NavigationController.PushViewController(callHistory, true);
                }
            };

            // Code for when CallButton is pressed
            CallButton.TouchUpInside += (object sender, EventArgs e) => {
                //store the phone number that we're dialing in PhoneNumbers
                // only if a number has been entered
                if (translatedNumber != "")
                {
                    PhoneNumbers.Add(translatedNumber);
                }

                //build the new url
                var url = new NSUrl("tel:" + translatedNumber);

                // Use URL handler with tel: prefix to invoke Apple's Phone app,
                // otherwise show an alert dialog

                if (!UIApplication.SharedApplication.OpenUrl(url))
                {
                    var av = new UIAlertView("Not supported",
                                             "Scheme 'tel:' is not supported on this device",
                                             null,
                                             "OK",
                                             null);
                    av.Show();
                }
            };
        }
        public static CFProxy[] GetProxiesForAutoConfigurationScript(NSString proxyAutoConfigurationScript, NSUrl targetURL)
        {
            if (proxyAutoConfigurationScript == null)
            {
                throw new ArgumentNullException("proxyAutoConfigurationScript");
            }

            if (targetURL == null)
            {
                throw new ArgumentNullException("targetURL");
            }

            using (var array = CopyProxiesForAutoConfigurationScript(proxyAutoConfigurationScript, targetURL)) {
                if (array == null)
                {
                    return(null);
                }

                NSDictionary[] dictionaries = NSArray.ArrayFromHandle <NSDictionary> (array.Handle);
                if (dictionaries == null)
                {
                    return(null);
                }

                CFProxy[] proxies = new CFProxy [dictionaries.Length];
                for (int i = 0; i < dictionaries.Length; i++)
                {
                    proxies [i] = new CFProxy(dictionaries [i]);
                }

                return(proxies);
            }
        }
Beispiel #57
0
        public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        {
            Distribute.OpenUrl(url);

            return(true);
        }
Beispiel #58
0
 public override string[] FilesDropped(NSOutlineView outlineView, NSUrl dropDestination, NSArray items)
 {
     throw new NotImplementedException();
 }
Beispiel #59
0
 public UIImage GetThumbnail(NSUrl atUri, CGSize withSize)
 {
     throw new NotImplementedException();
 }
 public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
 {
     //return base.OpenUrl(application, url, sourceApplication, annotation);
     return(ApplicationDelegate.SharedInstance.OpenUrl(application, url, sourceApplication, annotation));
 }