async partial void btnShare_Activated(UIBarButtonItem sender) { var text = string.Format("Grab yourself a {0}, its a great beer!", beer.Name); var items = new NSObject[] { new NSString (text) }; var activityController = new UIActivityViewController (items, null); await PresentViewControllerAsync (activityController, true); }
async partial void btnShare_Activated (UIBarButtonItem sender) { var text = viewModel.SharingMessage; var items = new NSObject[] { new NSString (text) }; var activityController = new UIActivityViewController (items, null); await PresentViewControllerAsync (activityController, true); }
public DetailViewController(RSSFeedItem item) : base(UITableViewStyle.Grouped, null, true) { var attributes = new NSAttributedStringDocumentAttributes(); attributes.DocumentType = NSDocumentType.HTML; attributes.StringEncoding = NSStringEncoding.UTF8; var error = new NSError(); var htmlString = new NSAttributedString(item.Description, attributes, ref error); Root = new RootElement(item.Title) { new Section{ new StringElement(item.Author), new StringElement(item.PublishDate), new StyledMultilineElement(htmlString), new HtmlElement("Full Article", item.Link) } }; NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, async delegate { var message = item.Title + " " + item.Link + " #PlanetXamarin"; var social = new UIActivityViewController(new NSObject[] { new NSString(message)}, new UIActivity[] { new UIActivity() }); PresentViewController(social, true, null); }); }
public void OnShareClicked(UIBarButtonItem button) { UIActivityViewController activityViewController = new UIActivityViewController (new NSObject[] { ImageView.Image }, null); var popover = activityViewController.PopoverPresentationController; if (popover != null) { popover.BarButtonItem = ShareItem; } // Set a completion handler to handle what the UIActivityViewController returns activityViewController.SetCompletionHandler ((activityType, completed, returnedItems, error) => { if (returnedItems == null || returnedItems.Length == 0) return; NSExtensionItem extensionItem = returnedItems [0]; NSItemProvider imageItemProvider = extensionItem.Attachments [0]; if (!imageItemProvider.HasItemConformingTo(UTType.Image)) return; imageItemProvider.LoadItem (UTType.Image, null, (item, loadError) => { if (item != null && loadError == null) InvokeOnMainThread (() => { ImageView.Image = (UIImage)item; }); }); }); PresentViewController (activityViewController, true, null); }
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); } }
private void ShowExtraMenu() { var sheet = MonoTouch.Utilities.GetSheet(Title); var openButton = sheet.AddButton("Open In".t()); var shareButton = ViewModel.HtmlUrl != null ? sheet.AddButton("Share".t()) : -1; var showButton = ViewModel.HtmlUrl != null ? sheet.AddButton("Show in Bitbucket".t()) : -1; var cancelButton = sheet.AddButton("Cancel".t()); sheet.CancelButtonIndex = cancelButton; sheet.DismissWithClickedButtonIndex(cancelButton, true); sheet.Clicked += (s, e) => { if (e.ButtonIndex == openButton) { var ctrl = new UIDocumentInteractionController(); ctrl.Url = NSUrl.FromFilename(ViewModel.FilePath); ctrl.PresentOpenInMenu(NavigationItem.RightBarButtonItem, true); } else if (e.ButtonIndex == shareButton) { var item = UIActivity.FromObject (ViewModel.HtmlUrl); var activityItems = new NSObject[] { item }; UIActivity[] applicationActivities = null; var activityController = new UIActivityViewController (activityItems, applicationActivities); PresentViewController (activityController, true, null); } else if (e.ButtonIndex == showButton) { ViewModel.GoToHtmlUrlCommand.Execute(null); } }; sheet.ShowInView(this.View); }
partial void ButtonShare_TouchUpInside(UIButton sender) { var items = new NSObject[] { new NSString("I just completed the #XamarinEvolve Quest and scored an awesome prize!") }; var activityController = new UIActivityViewController(items, null); PresentViewController(activityController, true, null); }
public void ShareUrl(string url) { var item = new NSUrl(new Uri(url).AbsoluteUri); var activityItems = new NSObject[] { item }; UIActivity[] applicationActivities = null; var activityController = new UIActivityViewController (activityItems, applicationActivities); _modalHost.PresentModalViewController(activityController, true); }
public override void OpenWith() { NSUrl url = NSUrl.FromFilename(path); RunInUI(() => { var ctrl = new UIActivityViewController(new NSObject[] { new NSString("Plain Text"), url }, null); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentModalViewController(ctrl, true); }); }
public void ShareScore(string level, string score) { string toShare = "I got " + score + " points on " + level + " in the ProgramADroid app. Can you beat me?"; UIActivityViewController activityShare = new UIActivityViewController( new NSObject[] { UIActivity.FromObject(toShare) }, null); this.NavigationController.PresentViewController(activityShare, true, null); }
public void ShareAchievement(string text) { string toShare = "Look at this achievement from the ProgramADroid app: " + text; UIActivityViewController activityShare = new UIActivityViewController( new NSObject[] { UIActivity.FromObject(toShare) }, null); this.NavigationController.PresentViewController(activityShare, true, null); }
public override void ViewDidLoad() { base.ViewDidLoad (); View.Subviews.OfType<UIButton>().Each( (button, n) => { button.TitleLabel.Font = UIFont.FromName ("Open Sans", 18f); }); View.Subviews.OfType<UILabel>().Each( (label, n) => { label.Font = UIFont.FromName ("Open Sans", 16f); }); CAGradientLayer gradient = CAGradientLayer.Create() as CAGradientLayer; gradient.Frame = View.Bounds; gradient.Colors = new MonoTouch.CoreGraphics.CGColor[] { UIColor.FromRGB(0, 0, 0).CGColor, UIColor.FromRGB(0, 71, 93).CGColor }; View.Layer.InsertSublayer(gradient, 0); if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) { twitterLink.Hidden = true; socialLink.Hidden = false; } else { twitterLink.Hidden = false; socialLink.Hidden = true; } twitterLink.TouchUpInside += (sender, e) => { var tweet = new TWTweetComposeViewController(); tweet.SetInitialText (mainViewController.GetSocialCountdownString()); PresentViewController(tweet, true, null); }; socialLink.TouchUpInside += (sender, e) => { var message = mainViewController.GetSocialCountdownString(); var social = new UIActivityViewController(new NSObject[] { new NSString(message)}, new UIActivity[] { new UIActivity() }); PresentViewController(social, true, null); }; websiteLink.TouchUpInside += (sender, e) => { var webUrl = NSUrl.FromString("http://daysuntilxmas.com"); UIApplication.SharedApplication.OpenUrl(webUrl); }; reviewLink.TouchUpInside += (sender, e) => { var id = "yourAppId"; var itunesUrl = NSUrl.FromString(String.Format("itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id={0}", id)); var webUrl = NSUrl.FromString(String.Format("http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id={0}&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", id)); if(UIApplication.SharedApplication.CanOpenUrl(itunesUrl)) UIApplication.SharedApplication.OpenUrl(itunesUrl); else UIApplication.SharedApplication.OpenUrl(webUrl); }; // Perform any additional setup after loading the view, typically from a nib. }
private void ShowActivitySheet(object sender, EventArgs e) { if (Element is ExtendedImage && ((ExtendedImage)Element).IsSharable) { var items = new NSObject[] { new NSString(((ExtendedImage)Element).ShareText), Control.Image }; var controller = new UIActivityViewController(items, null); UIApplication.SharedApplication.KeyWindow.RootViewController.GetTopViewController() .PresentViewController(controller, true, null); } }
async void ShareText(string text) { var item = NSObject.FromObject(text); var activityItems = new[] { item }; var activityController = new UIActivityViewController(activityItems, null); var topController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (topController.PresentedViewController != null) { topController = topController.PresentedViewController; } topController.PresentViewController(activityController, true, () => { }); }
void SharePlaceInfo (object sender, EventArgs e) { var message = new NSString (string.Format("{0}\n{1}\n{2}", viewModel.Place.Name, viewModel.Place.Website, viewModel.ShortAddress)); var activityController = new UIActivityViewController (new NSObject [] { message }, null); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { shareController = new UIPopoverController (activityController); shareController.PresentFromBarButtonItem(shareButton, UIPopoverArrowDirection.Any, true); } else { PresentViewController(activityController, true, null); } }
async void Share (ImageSource imageSource) { var handler = new ImageLoaderSourceHandler(); var uiImage = await handler.LoadImageAsync(imageSource); var item = NSObject.FromObject (uiImage); var activityItems = new[] { item }; var activityController = new UIActivityViewController (activityItems, null); var topController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (topController.PresentedViewController != null) { topController = topController.PresentedViewController; } topController.PresentViewController (activityController, true, () => {}); }
private static async Task ShareImageAsyc(ImageSource image, string message, string url = null) { var handler = image.GetHandler(); if (handler == null) return; var uiImage = await handler.LoadImageAsync(image); var items = new List<NSObject> { new NSString(message ?? string.Empty) }; if (!url.IsNullOrEmpty()) items.Add(new NSString(url)); items.Add(uiImage); var controller = new UIActivityViewController(items.ToArray(), null); UIApplication.SharedApplication.KeyWindow.RootViewController.GetTopViewController() .PresentViewController(controller, true, null); }
public void ShareUrl(string url) { var item = new NSUrl(new Uri(url).AbsoluteUri); var activityItems = new NSObject[] { item }; UIActivity[] applicationActivities = null; var activityController = new UIActivityViewController (activityItems, applicationActivities); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { var window = ((UIApplicationDelegate)UIApplication.SharedApplication.Delegate).Window; var pop = new UIPopoverController (activityController); pop.PresentFromRect (new CoreGraphics.CGRect (window.RootViewController.View.Frame.Width / 2, window.RootViewController.View.Frame.Height / 2, 0, 0), window.RootViewController.View, UIPopoverArrowDirection.Any, true); } else { _modalHost.PresentModalViewController(activityController, true); } }
/// <summary> /// Simply share text on compatible services /// </summary> /// <param name="text">Text to share</param> /// <param name="title">Title of popup on share (not included in message)</param> /// <returns>awaitable Task</returns> public async Task Share(string text, string title = null) { try { var items = new NSObject[] { new NSString(text ?? string.Empty) }; var activityController = new UIActivityViewController(items, null); if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = UIApplication.SharedApplication.KeyWindow.RootViewController.ChildViewControllers != null ? UIApplication.SharedApplication.KeyWindow.RootViewController.ChildViewControllers[0].View : UIApplication.SharedApplication.KeyWindow.RootViewController.View; } var vc = UIApplication.SharedApplication.KeyWindow.RootViewController; await vc.PresentViewControllerAsync(activityController, true); } catch (Exception ex) { Console.WriteLine("Unable to share text" + ex.Message); } }
private static void Share(UIViewController presentingViewController, string toShare) { var item = new NSString (toShare); var activityItems = new NSObject[] { item }; var activityViewController = new UIActivityViewController (activityItems, null); var excludedActivityTypes = new [] { UIActivityType.CopyToPasteboard, UIActivityType.Mail, UIActivityType.PostToWeibo }; if (!MFMessageComposeViewController.CanSendText) { excludedActivityTypes = new [] { UIActivityType.CopyToPasteboard, UIActivityType.Mail, UIActivityType.Message, UIActivityType.PostToWeibo }; } activityViewController.ExcludedActivityTypes = excludedActivityTypes; presentingViewController.PresentViewController (activityViewController, true, null); }
private void ShowActionSheet(string status, string title = "", string link = "") { link = link.Trim(); if (!string.IsNullOrWhiteSpace(link)) { var tempUri = new Uri(link); link = tempUri.GetLeftPart(UriPartial.Authority) + System.Web.HttpUtility.UrlPathEncode(tempUri.PathAndQuery); } var shareitem = new NSObject[] { new NSString(title), new NSUrl(link) }; var activityController = new UIActivityViewController(shareitem, null); activityController.SetValueForKey(new NSObject[] { new NSString(status) }.FirstOrDefault(), new NSString("subject")); //Would prefer this to popover from button on ipad if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = UIApplication.SharedApplication.KeyWindow.RootViewController.ChildViewControllers != null ? UIApplication.SharedApplication.KeyWindow.RootViewController.ChildViewControllers[0].View : UIApplication.SharedApplication.KeyWindow.RootViewController.View; } UIApplication.SharedApplication.KeyWindow.RootViewController.ShowViewController(activityController, new NSObject()); }
public void Initialise() { Switch.ValueChanged += delegate { file.Priority = Switch.On ? Priority.Highest : Priority.DoNotDownload; if (manager != null) { Manager.Singletone.UpdateMasterController(manager); } }; if (Share != null) { Share.TouchUpInside += delegate { var alert = UIAlertController.Create(file.Path, null, UIAlertControllerStyle.ActionSheet); var share = UIAlertAction.Create("Share", UIAlertActionStyle.Default, delegate { NSObject[] mass = { null, new NSUrl(file.FullPath, false) }; var shareController = new UIActivityViewController(mass, null); if (shareController.PopoverPresentationController != null) { shareController.PopoverPresentationController.SourceView = Share; shareController.PopoverPresentationController.SourceRect = Share.Bounds; shareController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any; } NSString[] set = { UIActivityType.PostToWeibo }; shareController.ExcludedActivityTypes = set; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(shareController, true, null); }); var delete = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate { var deleteController = UIAlertController.Create("Are you sure to delete?", file.Path, UIAlertControllerStyle.ActionSheet); var deleteAction = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate { if (manager.State == TorrentState.Stopped) { file.fileRemoved = true; Switch.SetState(false, true); file.Priority = Priority.DoNotDownload; UpdateInDetail(); if (File.Exists(file.FullPath)) { File.Delete(file.FullPath); } } else { var alertController = UIAlertController.Create("Error deleting file", "File cannot be removed while the download is in progress.\nStop the downloading first!", UIAlertControllerStyle.Alert); var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null); alertController.AddAction(ok); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alertController, true, null); } }); var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); deleteController.AddAction(deleteAction); deleteController.AddAction(cancelAction); if (deleteController.PopoverPresentationController != null) { deleteController.PopoverPresentationController.SourceView = Share; deleteController.PopoverPresentationController.SourceRect = Share.Bounds; deleteController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any; } UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(deleteController, true, null); }); var cancel = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); alert.AddAction(share); alert.AddAction(delete); alert.AddAction(cancel); if (alert.PopoverPresentationController != null) { alert.PopoverPresentationController.SourceView = Share; alert.PopoverPresentationController.SourceRect = Share.Bounds; alert.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Right; } UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null); }; } }
public void NewObjectDispose() { var obj = new UIActivityViewController("WOOT"); obj.Dispose(); }
public void Initialise() { Switch.ValueChanged += delegate { file.Priority = Switch.On ? Priority.Highest : Priority.DoNotDownload; if (manager != null) { Manager.Singletone.UpdateMasterController(manager); } }; if (Share != null) { Share.TouchUpInside += delegate { var alert = UIAlertController.Create(file.Path, null, UIAlertControllerStyle.ActionSheet); var share = UIAlertAction.Create("Share", UIAlertActionStyle.Default, delegate { NSObject[] mass = { null, new NSUrl(file.FullPath, false) }; var shareController = new UIActivityViewController(mass, null); if (shareController.PopoverPresentationController != null) { shareController.PopoverPresentationController.SourceView = Share; shareController.PopoverPresentationController.SourceRect = Share.Bounds; shareController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any; } NSString[] set = { UIActivityType.PostToWeibo }; shareController.ExcludedActivityTypes = set; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(shareController, true, null); }); var delete = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate { var deleteController = UIAlertController.Create("Are you sure to delete? (Not implemented yet!)", file.Path, UIAlertControllerStyle.ActionSheet); var deleteAction = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate { //TODO: Remove file and rehash it }); var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); deleteController.AddAction(deleteAction); deleteController.AddAction(cancelAction); if (deleteController.PopoverPresentationController != null) { deleteController.PopoverPresentationController.SourceView = Share; deleteController.PopoverPresentationController.SourceRect = Share.Bounds; deleteController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any; } UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(deleteController, true, null); }); var cancel = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); alert.AddAction(share); alert.AddAction(delete); alert.AddAction(cancel); if (alert.PopoverPresentationController != null) { alert.PopoverPresentationController.SourceView = Share; alert.PopoverPresentationController.SourceRect = Share.Bounds; alert.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Right; } UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null); }; } }
private UIButton CreateMoreButton(float x, double latitude, double longitude, bool isAlert = false) { var moreButton = new UIButton(UIButtonType.Custom); moreButton.Frame = new RectangleF(x, 4f, 30f, 30f); if (isAlert) { moreButton.SetImage(UIImage.FromBundle("MoreAlert"), UIControlState.Normal); } else { moreButton.SetImage(UIImage.FromBundle("More"), UIControlState.Normal); } moreButton.TouchUpInside += (s, e) => { var alert = AlertControllerHelper.CreateAlertOnMarkerMap(() => { var coordinate = new CLLocationCoordinate2D(latitude, longitude); var mapItem = new MKMapItem(new MKPlacemark(coordinate)); mapItem.OpenInMaps(new MKLaunchOptions() { MapCenter = coordinate }); } , () => { var item = FromObject(SeekiosApp.Helper.StringHelper.GoogleMapLinkShare(latitude, longitude)); var activityItems = new NSObject[] { item }; UIActivity[] applicationActivities = null; var activityController = new UIActivityViewController(activityItems, applicationActivities); if (_mapViewcontroller != null) { _mapViewcontroller.PresentViewController(activityController, true, null); } else if (_mapHistoriccontroller != null) { _mapHistoriccontroller.PresentViewController(activityController, true, null); } else if (_mapAllSeekios != null) { _mapAllSeekios.PresentViewController(activityController, true, null); } else if (_modeZonecontroller != null) { _modeZonecontroller.PresentViewController(activityController, true, null); } } , () => { var geoCode2 = new CLGeocoder(); geoCode2.ReverseGeocodeLocation(new CLLocation(latitude, longitude), (placemarks, error) => { if (placemarks?.Count() > 0) { UIPasteboard.General.String = FormatSeekiosAdress(placemarks.Last()); } else { var alert2 = AlertControllerHelper.CreateAlertOnMarkerMapNoAdress(); if (_mapViewcontroller != null) { _mapViewcontroller.PresentViewController(alert2, true, null); } else if (_mapHistoriccontroller != null) { _mapHistoriccontroller.PresentViewController(alert2, true, null); } else if (_mapAllSeekios != null) { _mapAllSeekios.PresentViewController(alert2, true, null); } else if (_modeZonecontroller != null) { _modeZonecontroller.PresentViewController(alert2, true, null); } } }); }); var geoCode = new CLGeocoder(); geoCode.ReverseGeocodeLocation(new CLLocation(latitude, longitude), (placemarks, error) => { if (placemarks?.Count() > 0) { alert.Title = FormatSeekiosAdress(placemarks.Last()); } else { alert.Title = Application.LocalizedString("NoAdressSeekios"); } }); if (_mapViewcontroller != null) { _mapViewcontroller.PresentViewController(alert, true, null); } else if (_mapHistoriccontroller != null) { _mapHistoriccontroller.PresentViewController(alert, true, null); } else if (_mapAllSeekios != null) { _mapAllSeekios.PresentViewController(alert, true, null); } else if (_modeZonecontroller != null) { _modeZonecontroller.PresentViewController(alert, true, null); } }; return(moreButton); }
public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow(indexPath, true); switch (indexPath.Row) { case 0: // users.get CallMethod(VKApi.Users.Get(new NSMutableDictionary <NSString, NSObject> { { VKApiConst.Fields, (NSString)"first_name, last_name, uid, photo_100" }, { VKApiConst.UserId, (NSNumber)OwnerId } })); break; case 1: // friends.get CallMethod(VKApi.Friends.Get()); break; case 2: // friends.get with fields var friendsRequest = VKApi.Friends.Get(new NSMutableDictionary <NSString, NSObject> { { VKApiConst.Fields, (NSString)AllUserFields } }); CallMethod(friendsRequest); break; case 3: // subscribers CallMethod(VKRequest.Create <VKUsersArray> ("users.getFollowers", new NSMutableDictionary <NSString, NSObject> { { VKApiConst.UserId, (NSNumber)FollowersId }, { VKApiConst.Count, (NSNumber)100 }, { VKApiConst.Fields, (NSString)AllUserFields } })); break; case 4: // Upload photo to wall UploadWallPhoto(); break; case 5: // Upload photo to album UploadAlbumPhoto(); break; case 6: // Upload several photos to wall UploadSeveralWallPhotos(); break; case 7: // Test captcha var request = new VKApiCaptcha().Force(); request.Execute( resp => Console.WriteLine("Result: " + resp), error => Console.WriteLine("Error: " + error)); break; case 8: // Call unknown method CallMethod(VKRequest.Create("I.am.Lord.Voldemort", null)); break; case 9: // Test validation CallMethod(VKRequest.Create("account.testValidation", null)); break; case 10: // Test share dialog var shareDialog = new VKShareDialogController(); shareDialog.Text = "This post made with #vksdk #xamarin #ios"; shareDialog.Images = new [] { PhotoId, PhotoId2, PhotoId3 }; shareDialog.ShareLink = new VKShareLink("Super puper link, but nobody knows", new NSUrl("https://vk.com/dev/ios_sdk")); shareDialog.DismissAutomatically = true; PresentViewController(shareDialog, true, null); break; case 11: // Test VKActivity var items = new NSObject [] { UIImage.FromBundle("apple"), (NSString)"This post made with #vksdk activity #xamarin #ios", new NSUrl("https://vk.com/dev/ios_sdk") }; var activityViewController = new UIActivityViewController(items, new [] { new VKActivity() }); activityViewController.SetValueForKey((NSString)"VK SDK", (NSString)"subject"); activityViewController.CompletionHandler = null; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var popover = activityViewController.PopoverPresentationController; if (popover != null) { popover.SourceView = View; popover.SourceRect = tableView.RectForRowAtIndexPath(indexPath); } } PresentViewController(activityViewController, false, null); break; case 12: // Test app request CallMethod(VKRequest.Create("apps.sendRequest", new NSMutableDictionary <NSString, NSObject> { { (NSString)"user_id", (NSNumber)FriendId }, { (NSString)"text", (NSString)"Yo ho ho" }, { (NSString)"type", (NSString)"request" }, { (NSString)"name", (NSString)"I need more gold" }, { (NSString)"key", (NSString)"more_gold" } })); break; } }
private void ShowExtraMenu() { var changeset = ViewModel.Changeset; if (changeset == null) return; var sheet = MonoTouch.Utilities.GetSheet(Title); var addComment = sheet.AddButton("Add Comment".t()); var copySha = sheet.AddButton("Copy Sha".t()); var shareButton = sheet.AddButton("Share".t()); //var showButton = sheet.AddButton("Show in GitHub".t()); var cancelButton = sheet.AddButton("Cancel".t()); sheet.CancelButtonIndex = cancelButton; sheet.DismissWithClickedButtonIndex(cancelButton, true); sheet.Clicked += (s, e) => { try { // Pin to menu if (e.ButtonIndex == addComment) { AddCommentTapped(); } else if (e.ButtonIndex == copySha) { UIPasteboard.General.String = ViewModel.Changeset.Sha; } else if (e.ButtonIndex == shareButton) { var item = new NSUrl(ViewModel.Changeset.Url); var activityItems = new MonoTouch.Foundation.NSObject[] { item }; UIActivity[] applicationActivities = null; var activityController = new UIActivityViewController (activityItems, applicationActivities); PresentViewController (activityController, true, null); } // else if (e.ButtonIndex == showButton) // { // ViewModel.GoToHtmlUrlCommand.Execute(null); // } } catch { } }; sheet.ShowInView(this.View); }
public override NSObject GetItemForActivity(UIActivityViewController activityViewController, NSString activityType) => item;
public override string GetSubjectForActivity(UIActivityViewController activityViewController, NSString activityType) => subject;
/// <summary> /// Programmatically initiates the user interface for sharing content with another app. /// </summary> public async static void ShowShareUI() { DataRequestedEventArgs e = new DataRequestedEventArgs(); instance.OnDataRequested(e); instance.currentDataPackage = e.Request.Data; DataPackageView view = instance.currentDataPackage.GetView(); if (view.AvailableFormats.Count > 0) { foreach (string format in view.AvailableFormats) { Debug.WriteLine(format); } #if __ANDROID__ string text = null; if (view.Contains(StandardDataFormats.Text)) { text = await view.GetTextAsync(); } else if (view.Contains(StandardDataFormats.WebLink)) { text = (await view.GetWebLinkAsync()).ToString(); } Intent shareIntent = new Intent(); shareIntent.SetAction(Intent.ActionSend); shareIntent.AddFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask); shareIntent.PutExtra(Intent.ExtraText, text); shareIntent.SetType("text/plain"); Intent shareChooserIntent = Intent.CreateChooser(shareIntent, "Share"); shareChooserIntent.AddFlags(ActivityFlags.ClearWhenTaskReset); Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(shareChooserIntent); //Platform.Android.ContextManager.Context.ApplicationContext.StartActivity(shareChooserIntent); #elif __IOS__ List <NSObject> values = new List <NSObject>(); if (view.Contains(StandardDataFormats.WebLink)) { values.Add(new NSUrl((await view.GetWebLinkAsync()).ToString())); } else if (view.Contains(StandardDataFormats.Text)) { values.Add(new NSString(await view.GetTextAsync())); } else if (view.Contains(StandardDataFormats.ApplicationLink)) { values.Add(new NSUrl((await view.GetApplicationLinkAsync()).ToString())); } UIActivityViewController activity = new UIActivityViewController(values.ToArray(), null); activity.CompletionWithItemsHandler = (text, success, items, error) => { if (success) { instance.OnTargetApplicationChosen(text); } else { Debug.WriteLine(error); } }; UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) { currentController = currentController.PresentedViewController; } currentController.PresentModalViewController(activity, true); #elif WINDOWS_PHONE /*if (view.Contains(StandardDataFormats.Bitmap)) * { * string path = view.GetBitmapFilename(); * if (string.IsNullOrEmpty(path)) * { * System.IO.Stream /Windows.Storage.Streams.RandomAccessStreamReference/ strRef = await view.GetBitmapAsync(); * Microsoft.Xna.Framework.Media.MediaLibrary ml = new Microsoft.Xna.Framework.Media.MediaLibrary(); * Microsoft.Xna.Framework.Media.Picture pic = ml.SavePicture("share", strRef); * path = Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions.GetPath(pic); * } * * Microsoft.Phone.Tasks.ShareMediaTask shareMediaTask = new Microsoft.Phone.Tasks.ShareMediaTask(); * shareMediaTask.FilePath = path; // "isostore:///shared/shellcontent/share.temp." + filename + ".png"; * shareMediaTask.Show(); * } * else * {*/ // for 8.0 apps running on 8.1 provide "light-up" to use shell sharing feature if (Environment.OSVersion.Version >= new Version(8, 10)) { if (view.Contains(StandardDataFormats.WebLink)) { Microsoft.Phone.Tasks.ShareLinkTask shareLinkTask = new Microsoft.Phone.Tasks.ShareLinkTask(); shareLinkTask.LinkUri = await view.GetWebLinkAsync(); shareLinkTask.Message = await view.GetTextAsync(); shareLinkTask.Title = view.Properties.Title; shareLinkTask.Show(); } else if (view.Contains(StandardDataFormats.ApplicationLink)) { Microsoft.Phone.Tasks.ShareLinkTask shareLinkTask = new Microsoft.Phone.Tasks.ShareLinkTask(); shareLinkTask.LinkUri = await view.GetApplicationLinkAsync(); shareLinkTask.Message = await view.GetTextAsync(); shareLinkTask.Title = view.Properties.Title; shareLinkTask.Show(); } else if (view.Contains(StandardDataFormats.Text)) { Microsoft.Phone.Tasks.ShareStatusTask shareStatusTask = new Microsoft.Phone.Tasks.ShareStatusTask(); shareStatusTask.Status = await view.GetTextAsync(); shareStatusTask.Show(); } } else { // use "custom" page to match OS 8.0 support ((Microsoft.Phone.Controls.PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/InTheHand.ApplicationModel;component/SharePage.xaml", UriKind.Relative)); } //} #endif } else { // nothing to share #if WINDOWS_PHONE //System.Windows.MessageBox.Show(Resources.Resources.NothingToShare, Resources.Resources.ShareHeader, MessageBoxButton.OK); #endif } }
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Forms.Init(); if (!Resolver.IsSet) { SetIoc(); } _lockService = Resolver.Resolve <ILockService>(); _deviceInfoService = Resolver.Resolve <IDeviceInfoService>(); _cipherService = Resolver.Resolve <ICipherService>(); _pushHandler = new iOSPushNotificationHandler(Resolver.Resolve <IPushNotificationListener>()); _nfcDelegate = new NFCReaderDelegate((success, message) => ProcessYubikey(success, message)); var appIdService = Resolver.Resolve <IAppIdService>(); var crashManagerDelegate = new HockeyAppCrashManagerDelegate( appIdService, Resolver.Resolve <IAuthService>()); var manager = BITHockeyManager.SharedHockeyManager; manager.Configure("51f96ae568ba45f699a18ad9f63046c3", crashManagerDelegate); manager.CrashManager.CrashManagerStatus = BITCrashManagerStatus.AutoSend; manager.UserId = appIdService.AppId; manager.StartManager(); manager.Authenticator.AuthenticateInstallation(); manager.DisableMetricsManager = manager.DisableFeedbackManager = manager.DisableUpdateManager = true; LoadApplication(new App.App( null, Resolver.Resolve <IAuthService>(), Resolver.Resolve <IConnectivity>(), Resolver.Resolve <IDatabaseService>(), Resolver.Resolve <ISyncService>(), Resolver.Resolve <ISettings>(), _lockService, Resolver.Resolve <ILocalizeService>(), Resolver.Resolve <IAppInfoService>(), Resolver.Resolve <IAppSettingsService>(), Resolver.Resolve <IDeviceActionService>())); // Appearance stuff var primaryColor = new UIColor(red: 0.24f, green: 0.55f, blue: 0.74f, alpha: 1.0f); var grayLight = new UIColor(red: 0.47f, green: 0.47f, blue: 0.47f, alpha: 1.0f); UINavigationBar.Appearance.ShadowImage = new UIImage(); UINavigationBar.Appearance.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); UIBarButtonItem.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).TintColor = primaryColor; UIButton.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).SetTitleColor(primaryColor, UIControlState.Normal); UIButton.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).TintColor = primaryColor; UIStepper.Appearance.TintColor = grayLight; UISlider.Appearance.TintColor = primaryColor; MessagingCenter.Subscribe <Xamarin.Forms.Application, ToolsExtensionPage>( Xamarin.Forms.Application.Current, "ShowAppExtension", (sender, page) => { var itemProvider = new NSItemProvider(new NSDictionary(), Core.Constants.UTTypeAppExtensionSetup); var extensionItem = new NSExtensionItem(); extensionItem.Attachments = new NSItemProvider[] { itemProvider }; var activityViewController = new UIActivityViewController(new NSExtensionItem[] { extensionItem }, null); activityViewController.CompletionHandler = (activityType, completed) => { page.EnabledExtension(completed && activityType == "com.8bit.bitwarden.find-login-action-extension"); }; var modal = UIApplication.SharedApplication.KeyWindow.RootViewController.ModalViewController; if (activityViewController.PopoverPresentationController != null) { activityViewController.PopoverPresentationController.SourceView = modal.View; var frame = UIScreen.MainScreen.Bounds; frame.Height /= 2; activityViewController.PopoverPresentationController.SourceRect = frame; } modal.PresentViewController(activityViewController, true, null); }); MessagingCenter.Subscribe <Xamarin.Forms.Application, bool>( Xamarin.Forms.Application.Current, "ListenYubiKeyOTP", (sender, listen) => { if (_deviceInfoService.NfcEnabled) { _nfcSession?.InvalidateSession(); _nfcSession?.Dispose(); _nfcSession = null; if (listen) { _nfcSession = new NFCNdefReaderSession(_nfcDelegate, null, true); _nfcSession.AlertMessage = AppResources.HoldYubikeyNearTop; _nfcSession.BeginSession(); } } }); UIApplication.SharedApplication.StatusBarHidden = false; UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent; MessagingCenter.Subscribe <Xamarin.Forms.Application, bool>( Xamarin.Forms.Application.Current, "ShowStatusBar", (sender, show) => { UIApplication.SharedApplication.SetStatusBarHidden(!show, false); }); MessagingCenter.Subscribe <Xamarin.Forms.Application, bool>( Xamarin.Forms.Application.Current, "FullSyncCompleted", async(sender, successfully) => { if (_deviceInfoService.Version >= 12 && successfully) { await ASHelpers.ReplaceAllIdentities(_cipherService); } }); MessagingCenter.Subscribe <Xamarin.Forms.Application, Tuple <string, bool> >( Xamarin.Forms.Application.Current, "UpsertedCipher", async(sender, data) => { if (_deviceInfoService.Version >= 12) { if (await ASHelpers.IdentitiesCanIncremental()) { if (data.Item2) { var identity = await ASHelpers.GetCipherIdentityAsync(data.Item1, _cipherService); if (identity == null) { return; } await ASCredentialIdentityStore.SharedStore?.SaveCredentialIdentitiesAsync( new ASPasswordCredentialIdentity[] { identity }); return; } } await ASHelpers.ReplaceAllIdentities(_cipherService); } }); MessagingCenter.Subscribe <Xamarin.Forms.Application, Cipher>( Xamarin.Forms.Application.Current, "DeletedCipher", async(sender, cipher) => { if (_deviceInfoService.Version >= 12) { if (await ASHelpers.IdentitiesCanIncremental()) { var identity = ASHelpers.ToCredentialIdentity(cipher); if (identity == null) { return; } await ASCredentialIdentityStore.SharedStore?.RemoveCredentialIdentitiesAsync( new ASPasswordCredentialIdentity[] { identity }); return; } await ASHelpers.ReplaceAllIdentities(_cipherService); } }); MessagingCenter.Subscribe <Xamarin.Forms.Application>( Xamarin.Forms.Application.Current, "LoggedOut", async(sender) => { if (_deviceInfoService.Version >= 12) { await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync(); } }); ZXing.Net.Mobile.Forms.iOS.Platform.Init(); return(base.FinishedLaunching(app, options)); }
public override void ViewDidAppear(bool animated) { this.appDelegate.tablePDFSearch = 0; UIBarButtonItem searchText = new UIBarButtonItem(UIBarButtonSystemItem.Search, (object sender, EventArgs e) => { //searches for matching text inside pdf this.searchForText.Placeholder = "Search..."; this.searchForText.SpellCheckingType = UITextSpellCheckingType.No; this.searchForText.SearchBarStyle = UISearchBarStyle.Prominent; this.searchForText.BarStyle = UIBarStyle.Default; this.searchForText.ShowsCancelButton = true; this.NavigationItem.TitleView = this.searchForText; this.searchForText.BecomeFirstResponder(); this.searchForText.CancelButtonClicked += (object sender_2, EventArgs e_2) => { //replaces the navigation item with the title text this.searchForText.ResignFirstResponder(); this.NavigationItem.TitleView = null; this.NavigationItem.Title = "Viewer"; }; }); UIBarButtonItem pageMode = new UIBarButtonItem("Page Mode", UIBarButtonItemStyle.Done, (object sender, EventArgs e) => { //page count is adjusted //creates a small table which adjusts the number of pages to render //an alert controller is best for this if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIAlertController pageModeController = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet); UIAlertAction onePage = UIAlertAction.Create("Single Page", UIAlertActionStyle.Default, (UIAlertAction obj) => { this.pdfWebReader.PaginationMode = UIWebPaginationMode.TopToBottom; pageModeController.Dispose(); }); UIAlertAction continousPages = UIAlertAction.Create("Continuous", UIAlertActionStyle.Default, (UIAlertAction obj) => { this.pdfWebReader.PaginationMode = UIWebPaginationMode.Unpaginated; pageModeController.Dispose(); }); UIAlertAction denied = UIAlertAction.Create("Never Mind", UIAlertActionStyle.Cancel, (UIAlertAction obj) => { pageModeController.Dispose(); }); pageModeController.AddAction(onePage); pageModeController.AddAction(continousPages); pageModeController.AddAction(denied); if (this.PresentedViewController == null) { this.PresentViewController(pageModeController, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(pageModeController, true, null); }); } } else { UIAlertController pageModeController = UIAlertController.Create("", "", UIAlertControllerStyle.Alert); UIAlertAction onePage = UIAlertAction.Create("Single Page", UIAlertActionStyle.Default, (UIAlertAction obj) => { this.pdfWebReader.PaginationMode = UIWebPaginationMode.TopToBottom; pageModeController.Dispose(); }); UIAlertAction continousPages = UIAlertAction.Create("Full Screen", UIAlertActionStyle.Default, (UIAlertAction obj) => { this.pdfWebReader.PaginationMode = UIWebPaginationMode.Unpaginated; pageModeController.Dispose(); }); UIAlertAction denied = UIAlertAction.Create("Never Mind", UIAlertActionStyle.Cancel, (UIAlertAction obj) => { pageModeController.Dispose(); }); pageModeController.AddAction(onePage); pageModeController.AddAction(continousPages); pageModeController.AddAction(denied); if (this.PresentedViewController == null) { this.PresentViewController(pageModeController, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(pageModeController, true, null); }); } } }); UIBarButtonItem share = new UIBarButtonItem(UIBarButtonSystemItem.Action, (sender, e) => { //introduces an action sheet. with the following options: /* * allows the user to share file (which creates an activity controller where the user can choose how to share the file) * allows updating to the cloud * allows an option to open the document in another application of choice (UIDocumentInterationController) * Print the document (In a nearby printer via AirPrint) * */ if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIAlertController shareModeController = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet); UIAlertAction shareFile = UIAlertAction.Create("Share File", UIAlertActionStyle.Default, (UIAlertAction obj) => { var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var filePath = Path.Combine(directory, this.appDelegate.pdfString); NSUrl pdfURL = NSUrl.FromFilename(filePath); NSData pdfData = NSData.FromUrl(pdfURL); NSObject[] dataToShare = new NSObject[] { pdfURL }; UIActivityViewController activity = new UIActivityViewController(dataToShare, null); //UIActivityType[] activityTypes = new UIActivityType[] { UIActivityType.Print, UIActivityType.SaveToCameraRoll }; if (this.PresentedViewController == null) { this.PresentViewController(activity, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(activity, true, null); }); } shareModeController.Dispose(); }); UIAlertAction printDocument = UIAlertAction.Create("Print Document", UIAlertActionStyle.Default, (UIAlertAction obj) => { var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var filePath = Path.Combine(directory, this.appDelegate.pdfString); NSUrl pdfURL = NSUrl.FromFilename(filePath); var printInformation = UIPrintInfo.PrintInfo; printInformation.OutputType = UIPrintInfoOutputType.General; printInformation.JobName = "Print Job"; var print = UIPrintInteractionController.SharedPrintController; print.PrintInfo = printInformation; print.PrintFormatter = this.pdfWebReader.ViewPrintFormatter; print.PrintingItem = pdfURL; print.ShowsPageRange = true; if (UIPrintInteractionController.CanPrint(pdfURL) == true) { print.Present(true, (UIPrintInteractionController printInteractionController, bool completed, NSError error) => { if (error != null) { print.Dismiss(true); errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected"); } else { Console.WriteLine("Printer success"); } }); } else { errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected"); } shareModeController.Dispose(); }); UIAlertAction denied = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) => { shareModeController.Dispose(); }); shareModeController.AddAction(shareFile); shareModeController.AddAction(printDocument); shareModeController.AddAction(denied); if (this.PresentedViewController == null) { this.PresentViewController(shareModeController, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(shareModeController, true, null); }); } } else { UIAlertController shareModeController = UIAlertController.Create("", "", UIAlertControllerStyle.Alert); UIAlertAction shareFile = UIAlertAction.Create("Share File", UIAlertActionStyle.Default, (UIAlertAction obj) => { var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var filePath = Path.Combine(directory, this.appDelegate.pdfString); NSUrl pdfURL = NSUrl.FromFilename(filePath); NSData pdfData = NSData.FromUrl(pdfURL); NSObject[] dataToShare = new NSObject[] { pdfURL }; UIActivityViewController activity = new UIActivityViewController(dataToShare, null); //UIActivityType[] activityTypes = new UIActivityType[] { UIActivityType.Print, UIActivityType.SaveToCameraRoll }; if (this.PresentedViewController == null) { this.PresentViewController(activity, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(activity, true, null); }); } shareModeController.Dispose(); }); UIAlertAction printDocument = UIAlertAction.Create("Print Document", UIAlertActionStyle.Default, (UIAlertAction obj) => { var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var filePath = Path.Combine(directory, this.appDelegate.pdfString); NSUrl pdfURL = NSUrl.FromFilename(filePath); var printInformation = UIPrintInfo.PrintInfo; printInformation.OutputType = UIPrintInfoOutputType.General; printInformation.JobName = "Print Job"; var print = UIPrintInteractionController.SharedPrintController; print.PrintInfo = printInformation; print.PrintFormatter = this.pdfWebReader.ViewPrintFormatter; print.PrintingItem = pdfURL; print.ShowsPageRange = true; print.Present(true, (UIPrintInteractionController printInteractionController, bool completed, NSError error) => { if (error != null) { print.Dismiss(true); errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected"); } else { Console.WriteLine("Printer success"); } }); shareModeController.Dispose(); }); UIAlertAction denied = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) => { shareModeController.Dispose(); }); shareModeController.AddAction(shareFile); shareModeController.AddAction(printDocument); shareModeController.AddAction(denied); if (this.PresentedViewController == null) { this.PresentViewController(shareModeController, true, null); } else { this.PresentedViewController.DismissViewController(true, () => { this.PresentedViewController.Dispose(); this.PresentViewController(shareModeController, true, null); }); } } }); UIBarButtonItem writeComment = new UIBarButtonItem("Comment", UIBarButtonItemStyle.Done, (sender, e) => { //adjusts the toolbar items with drawing items used for drawing items on the PDF view controller }); this.NavigationController.SetToolbarHidden(false, true); UIBarButtonItem space_1 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null); UIBarButtonItem space_2 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null); this.NavigationController.Toolbar.Items = new UIBarButtonItem[] { searchText, space_1, space_2, share }; }
void sharebox() // share files UIActivityViewController { List <NSObject> activityItems = new List <NSObject>(); List <string> delfile = new List <string>(); // NSObject[] j = lis.ToArray<NSObject>(); foreach (iEbutton ep in UIbutton) { if (ep.BackboolSlect()) { if (ep._isvideor()) { string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = ep.setText(); //same if I save the file as .mp4 var localPath = Path.Combine(documentsPath, localFilename); File.WriteAllBytes(localPath, ep.retbyet()); var url = NSUrl.FromFilename(localPath); var videoToShare = url.Copy(); activityItems.Add(videoToShare); delfile.Add(localPath); } else { activityItems.Add(ep.image()); } } } // _Select = false; // var activityItems = lis.ToArray<NSObject>(); //int i = 0; //while (i < lis.Count) { activityItems[i] = lis[i]; i++; } // var imageToShare = UIbutton[0].image(); // var activityItems = new NSObject[] { imageToShare}; //var ii = NSUrl.FromFilename(local); //var imageToShare = ii.Copy(); //var activityItems = new NSObject[] { imageToShare }; var controller = new UIActivityViewController(activityItems.ToArray <NSObject>(), null); this.PresentViewController(controller, true, null); // new Thread(() => { Thread.Sleep(1000); foreach (string d in delfile) { File.Delete(d); } }); }
public override NSObject GetPlaceholderData(UIActivityViewController activityViewController) { return(TextStream); }
public override string GetDataTypeIdentifierForActivity(UIActivityViewController activityViewController, NSString activityType) { // let iOS know that we can offer it as simply as plain text. return("public.plain-text"); }
public override string GetSubjectForActivity(UIActivityViewController activityViewController, NSString activityType) { return($"Check out {song}"); }
async Task ExecuteShareBlobCommandAsync() { if (IsBusy) { return; } App.Logger.Track(AppEvent.ShareBlob.ToString()); if (HasBlobBeenSaved) { try { #if __ANDROID__ string mimeType = MediaTypeMapper.GetMimeType(BlobFileExtension); Android.Net.Uri uri = Android.Net.Uri.Parse("file:///" + GetBlobFilePath()); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(uri, mimeType); intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask); try { Xamarin.Forms.Forms.Context.StartActivity(intent); } catch (Exception ex) { MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert { Title = "Unable to Share", Message = "No applications available to open files of type " + BlobFileExtension, Cancel = "OK" }); throw ex; } #elif __IOS__ var extensionClassRef = new NSString(UTType.TagClassFilenameExtension); var mimeTypeClassRef = new NSString(UTType.TagClassMIMEType); var uti = NativeTools.UTTypeCreatePreferredIdentifierForTag(extensionClassRef.Handle, new NSString(BlobFileExtension).Handle, IntPtr.Zero); //TODO: open file based off of type var fi = NSData.FromFile(GetBlobFilePath()); var item = NSObject.FromObject(fi); var activityItems = new[] { item }; var activityController = new UIActivityViewController(activityItems, null); var topController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (topController.PresentedViewController != null) { topController = topController.PresentedViewController; } topController.PresentViewController(activityController, true, () => { }); #endif } catch (Exception ex) { App.Logger.Report(ex, Severity.Error); } } }
/// /// Shares an image using the preferred method in Android or iOS. /// /// Path. public async Task ShareImage(string path, string extratxt = "") { try { #if ANDROID // Set up the Share Intent var shareIntent = new Intent(Intent.ActionSend); // Add Text to go along with it shareIntent.PutExtra(Intent.ExtraText, extratxt); // The link to the photo you want to share (i.e the path to the saved screenshot) var photoFile = new Java.IO.File(path); var uri = Uri.FromFile(photoFile); // Add the required info the the shareIntent shareIntent.PutExtra(Intent.ExtraStream, uri); shareIntent.SetType("image/*"); shareIntent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask); // Now Send the Share Intent var chooserIntent = Intent.CreateChooser(shareIntent, "Choose one"); chooserIntent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask); CrossCurrentActivity.Current.AppContext.StartActivity(chooserIntent); //// Now Send the Share Intent //Application.Context.StartActivity(Intent.CreateChooser(shareIntent, "Choose one")); #elif __IOS__ UIApplication.SharedApplication.InvokeOnMainThread(delegate { var viewController = Game.Services.GetService <UIViewController>(); var file = NSFileManager.DefaultManager.Contents(path); var tempUrl = NSUrl.CreateFileUrl(new string[] { path }); var itemsToShare = new NSObject[] { tempUrl }; UIActivityViewController activityViewController = new UIActivityViewController(itemsToShare, null); activityViewController.ExcludedActivityTypes = new NSString[] { }; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { activityViewController.PopoverPresentationController.SourceView = viewController.View; activityViewController.PopoverPresentationController.SourceRect = new CoreGraphics.CGRect((viewController.View.Bounds.Width / 2), (viewController.View.Bounds.Height / 4), 0, 0); } viewController.PresentViewController(activityViewController, true, null); }); #else var messageDisplay = Game.Services.GetService <IToastBuddy>(); messageDisplay.ShowMessage($"Sharing not available on this platform", Color.Yellow); #endif } catch (Exception ex) { var messageDisplay = Game.Services.GetService <IToastBuddy>(); messageDisplay.ShowMessage($"Error sharing image", Color.Yellow); var screenManager = Game.Services.GetService <IScreenManager>(); await screenManager.AddScreen(new OkScreen(ex.Message)); } }
void CleanupActivity() { activityViewController = null; }
public override void ViewDidLoad() { base.ViewDidLoad(); View.Subviews.OfType <UIButton>().Each((button, n) => { button.TitleLabel.Font = UIFont.FromName("Open Sans", 18f); }); View.Subviews.OfType <UILabel>().Each((label, n) => { label.Font = UIFont.FromName("Open Sans", 16f); }); CAGradientLayer gradient = CAGradientLayer.Create() as CAGradientLayer; gradient.Frame = View.Bounds; gradient.Colors = new MonoTouch.CoreGraphics.CGColor[] { UIColor.FromRGB(0, 0, 0).CGColor, UIColor.FromRGB(0, 71, 93).CGColor }; View.Layer.InsertSublayer(gradient, 0); if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { twitterLink.Hidden = true; socialLink.Hidden = false; } else { twitterLink.Hidden = false; socialLink.Hidden = true; } twitterLink.TouchUpInside += (sender, e) => { var tweet = new TWTweetComposeViewController(); tweet.SetInitialText(mainViewController.GetSocialCountdownString()); PresentViewController(tweet, true, null); }; socialLink.TouchUpInside += (sender, e) => { var message = mainViewController.GetSocialCountdownString(); var social = new UIActivityViewController(new NSObject[] { new NSString(message) }, new UIActivity[] { new UIActivity() }); PresentViewController(social, true, null); }; websiteLink.TouchUpInside += (sender, e) => { var webUrl = NSUrl.FromString("http://daysuntilxmas.com"); UIApplication.SharedApplication.OpenUrl(webUrl); }; reviewLink.TouchUpInside += (sender, e) => { var id = "yourAppId"; var itunesUrl = NSUrl.FromString(String.Format("itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id={0}", id)); var webUrl = NSUrl.FromString(String.Format("http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id={0}&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", id)); if (UIApplication.SharedApplication.CanOpenUrl(itunesUrl)) { UIApplication.SharedApplication.OpenUrl(itunesUrl); } else { UIApplication.SharedApplication.OpenUrl(webUrl); } }; // Perform any additional setup after loading the view, typically from a nib. }
public override void ShareFileAsync(string path, string subject) { Device.BeginInvokeOnMainThread(() => { ShareFileActivityItemSource activityItemSource = new ShareFileActivityItemSource(path, subject); UIActivityViewController shareActivity = new UIActivityViewController(new NSObject[] { activityItemSource }, null); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(shareActivity, true, null); }); }
private void Share(object state) { var activityController = new UIActivityViewController(new NSObject[] { new NSString(state.ToString()) }, null); this.PresentViewController(activityController, true, null); }
public override NSObject GetPlaceholderData(UIActivityViewController activityViewController) => item;
private static async Task <bool> ShowShareUIAsync(ShareUIOptions options, DataPackage dataPackage) { var rootViewController = UIApplication.SharedApplication?.KeyWindow?.RootViewController; if (rootViewController == null) { if (_instance.Value.Log().IsEnabled(LogLevel.Error)) { _instance.Value.Log().LogError("The Share API was called too early in the application lifecycle"); } return(false); } var dataPackageView = dataPackage.GetView(); var sharedData = new List <NSObject>(); var title = dataPackage.Properties.Title ?? string.Empty; if (dataPackageView.Contains(StandardDataFormats.Text)) { var text = await dataPackageView.GetTextAsync(); sharedData.Add(new DataActivityItemSource(new NSString(text), title)); } var uri = await GetSharedUriAsync(dataPackageView); if (uri != null) { sharedData.Add(new DataActivityItemSource(NSUrl.FromString(uri.OriginalString), title)); } var activityViewController = new UIActivityViewController(sharedData.ToArray(), null); if (activityViewController.PopoverPresentationController != null && rootViewController.View != null) { activityViewController.PopoverPresentationController.SourceView = rootViewController.View; if (options.SelectionRect != null) { activityViewController.PopoverPresentationController.SourceRect = options.SelectionRect.Value.ToCGRect(); } else { activityViewController.PopoverPresentationController.SourceRect = new CGRect(rootViewController.View.Bounds.Width / 2, rootViewController.View.Bounds.Height / 2, 0, 0); activityViewController.PopoverPresentationController.PermittedArrowDirections = 0; } } if (options.Theme != ShareUITheme.Default) { activityViewController.OverrideUserInterfaceStyle = options.Theme == ShareUITheme.Light ? UIUserInterfaceStyle.Light : UIUserInterfaceStyle.Dark; } else { // Theme should match the application theme activityViewController.OverrideUserInterfaceStyle = CoreApplication.RequestedTheme == SystemTheme.Light ? UIUserInterfaceStyle.Light : UIUserInterfaceStyle.Dark; } var completionSource = new TaskCompletionSource <bool>(); activityViewController.CompletionWithItemsHandler = (NSString activityType, bool completed, NSExtensionItem[] returnedItems, NSError error) => { completionSource.SetResult(completed); }; await rootViewController.PresentViewControllerAsync(activityViewController, true); return(await completionSource.Task); }
public override NSObject GetPlaceholderData(UIActivityViewController activityViewController) { return(new NSObject()); }
void DisplayActivityViewController(UIActivityViewController controller, bool animated) { PresentViewController(controller, animated, null); }
/// <summary> /// Shows the native UIActivityViewController to share message, images, and URLs /// via Facebook, Twitter, Weibo, email, SMS, print, copy, save to camera roll, or /// assign to contact. /// Raises ShareCompleted event when completed. /// </summary> /// <remarks> /// This is available in iOS 6.0 and later.</remarks> /// /// <param name="items"> An array of items to share. Each item can be a string, NSURL, Texture2D, or UIImage. /// Strings starting with http:// or https:// will be automatically converted to URLs.</param> /// <param name="excludedActivityTypes"> An array of strings representing the activity types to exclude from sharing. /// See <see cref="UIActivity">Constants in UIActivity</see>.</param> public static void Share(object[] items, string[] excludedActivityTypes = null) { var nativeItems = new object[items.Length]; for (int i = 0; i < items.Length; i++) { var item = items[i]; if (item is string) { string str = item as string; if (str.StartsWith("http://") || str.StartsWith("https://")) { nativeItems[i] = new NSURL(str); } else { nativeItems[i] = str; } } else if (item is Texture2D) { nativeItems[i] = UIImage.FromTexture2D(item as Texture2D); } else if (item is UIImage) { nativeItems[i] = item; } else if (item is NSURL) { nativeItems[i] = item; } else { throw new U3DXTException("Unexpected item type: " + item.GetType()); } } var vc = new UIActivityViewController(nativeItems, null); if (vc.IsNil) { return; } vc.completionHandler = _activityViewCompleted; if (excludedActivityTypes != null) { vc.excludedActivityTypes = excludedActivityTypes; } var rootVc = UIApplication.deviceRootViewController; if (CoreXT.IsiPad) { if (_popover == null) { _popover = new UIPopoverController(vc); } else { _popover.contentViewController = vc; } var rect = rootVc.view.bounds; rect.x = rect.width / 2; rect.y = rect.height; rect.width = 1; rect.height = 1; _popover.PresentPopover( rect, rootVc.view, UIPopoverArrowDirection.Down, true); } else { rootVc.PresentViewController(vc, true, null); } }
public override NSObject GetItemForActivity(UIActivityViewController _, NSString __) => Item;
public void Share(string content) { var activityViewController = new UIActivityViewController(new NSString[] { new NSString(content) }, null); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(activityViewController, true, null); }
public override string GetSubjectForActivity(UIActivityViewController _, NSString __) => Subject;
async partial void actionClicked (UIBarButtonItem sender) { var annotatedImage = AnnotateView.IncrementImage; if (annotatedImage != null) { var firstActivityItem = annotatedImage.AsJPEG(1); var applicationActivities = new List<UIActivity> (); // var donedoneActivity = BtTrackerActivity(TrackerType.DoneDone); applicationActivities.Add(new BtTrackerActivity (TrackerType.DoneDone)); applicationActivities.Add(new BtTrackerActivity (TrackerType.PivotalTracker)); applicationActivities.Add(new BtTrackerActivity (TrackerType.JIRA)); var activityViewController = new UIActivityViewController (new [] { firstActivityItem }, applicationActivities.ToArray()); activityViewController.ExcludedActivityTypes = new [] { UIActivityType.PostToWeibo, UIActivityType.AddToReadingList, UIActivityType.PostToVimeo, UIActivityType.PostToTencentWeibo }; // This doesn't get called for the custom activities (BtTrackerActivity) activityViewController.SetCompletionHandler((activityType, completed, returnedItems, error) => { if (completed) { // if (activityType != null) Analytics.Shared.Activity(activityType.ToString(), true); Console.WriteLine("{0} -- Completed", activityType); } else if (error != null) { Console.WriteLine(error.LocalizedDescription); //Log.Error("UIActivityViewController", error.LocalizedDescription); } else if (activityType != null) { Console.WriteLine("{0} -- Cancelled", activityType); // Analytics.Shared.Activity(activityType.ToString(), false); } }); // set the action but as the popover's anchor for ipad if (activityViewController.PopoverPresentationController != null) { activityViewController.PopoverPresentationController.BarButtonItem = actionButton; } // has the image been altered? if (AnnotateView.ImageHasChanges) await TrapState.Shared.UpdateActiveSnapshotImage(annotatedImage); NavigationController.PresentViewController(activityViewController, true, null); } }
public override string GetDataTypeIdentifierForActivity(UIActivityViewController activityViewController, NSString activityType) { return "edu.virginia.sie.ptl.sensus.protocol"; }
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); if (!Resolver.IsSet) { SetIoc(); } var appIdService = Resolver.Resolve <IAppIdService>(); var crashManagerDelegate = new HockeyAppCrashManagerDelegate( appIdService, Resolver.Resolve <IAuthService>()); var manager = BITHockeyManager.SharedHockeyManager; manager.Configure("51f96ae568ba45f699a18ad9f63046c3", crashManagerDelegate); manager.CrashManager.CrashManagerStatus = BITCrashManagerStatus.AutoSend; manager.UserId = appIdService.AppId; manager.StartManager(); manager.Authenticator.AuthenticateInstallation(); manager.DisableMetricsManager = manager.DisableFeedbackManager = manager.DisableUpdateManager = true; LoadApplication(new App.App( null, Resolver.Resolve <IAuthService>(), Resolver.Resolve <IConnectivity>(), Resolver.Resolve <IUserDialogs>(), Resolver.Resolve <IDatabaseService>(), Resolver.Resolve <ISyncService>(), Resolver.Resolve <IFingerprint>(), Resolver.Resolve <ISettings>(), Resolver.Resolve <ILockService>(), Resolver.Resolve <IGoogleAnalyticsService>(), Resolver.Resolve <ILocalizeService>())); // Appearance stuff var primaryColor = new UIColor(red: 0.24f, green: 0.55f, blue: 0.74f, alpha: 1.0f); var grayLight = new UIColor(red: 0.47f, green: 0.47f, blue: 0.47f, alpha: 1.0f); UINavigationBar.Appearance.ShadowImage = new UIImage(); UINavigationBar.Appearance.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); UIBarButtonItem.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).TintColor = primaryColor; UIButton.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).SetTitleColor(primaryColor, UIControlState.Normal); UIButton.AppearanceWhenContainedIn(new Type[] { typeof(UISearchBar) }).TintColor = primaryColor; UIStepper.Appearance.TintColor = grayLight; UISlider.Appearance.TintColor = primaryColor; MessagingCenter.Subscribe <Xamarin.Forms.Application, ToolsExtensionPage>(Xamarin.Forms.Application.Current, "ShowAppExtension", (sender, page) => { var itemProvider = new NSItemProvider(new NSDictionary(), iOS.Core.Constants.UTTypeAppExtensionSetup); var extensionItem = new NSExtensionItem(); extensionItem.Attachments = new NSItemProvider[] { itemProvider }; var activityViewController = new UIActivityViewController(new NSExtensionItem[] { extensionItem }, null); activityViewController.CompletionHandler = (activityType, completed) => { page.EnabledExtension(completed && activityType == "com.8bit.bitwarden.find-login-action-extension"); }; var modal = UIApplication.SharedApplication.KeyWindow.RootViewController.ModalViewController; if (activityViewController.PopoverPresentationController != null) { activityViewController.PopoverPresentationController.SourceView = modal.View; var frame = UIScreen.MainScreen.Bounds; frame.Height /= 2; activityViewController.PopoverPresentationController.SourceRect = frame; } modal.PresentViewController(activityViewController, true, null); }); UIApplication.SharedApplication.StatusBarHidden = false; UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent; MessagingCenter.Subscribe <Xamarin.Forms.Application, bool>(Xamarin.Forms.Application.Current, "ShowStatusBar", (sender, show) => { UIApplication.SharedApplication.SetStatusBarHidden(!show, false); }); return(base.FinishedLaunching(app, options)); }
public override NSObject GetItemForActivity(UIActivityViewController activityViewController, Foundation.NSString activityType) { return NSData.FromUrl(NSUrl.FromFilename(_path)); }
public async Task PerformActionOnDocument (DocumentReference docRef, UIViewController fromController, UIBarButtonItem fromButton) { try { if (docRef == null) return; var ad = this; if (ad.DismissSheetsAndPopovers ()) return; NSObject[] items = new NSObject[0]; UIActivity[] aa = new UIActivity[0]; try { var d = (await docRef.Open ()) as TextDocument; if (d != null) { items = await d.GetActivityItemsAsync (fromController); aa = await d.GetActivitiesAsync (fromController); } await docRef.Close (); } catch (Exception ex) { Debug.WriteLine (ex); } if (items.Length > 0) { var tcs = new TaskCompletionSource<bool> (); var a = new UIActivityViewController (items, aa); a.ModalPresentationStyle = UIModalPresentationStyle.Popover; a.CompletionHandler = (x,success) => { Console.WriteLine ("COMPLETE {0} {1}", x, success); tcs.SetResult (success); }; if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { if (a.PopoverPresentationController != null) { try { a.PopoverPresentationController.BarButtonItem = fromButton; } catch (Exception) { a.PopoverPresentationController.SourceView = fromController.View; } } } fromController.PresentViewController (a, true, null); await tcs.Task; } } catch (Exception ex) { Console.WriteLine ("Perform Act of Doc Failed: " + ex); } }
public override NSObject GetPlaceholderData(UIActivityViewController activityViewController) { return new NSString(_subject); }
public override void ViewDidLoad () { base.ViewDidLoad (); if(!Application.IsiOS7) View.BackgroundColor = UIColor.LightGray; NSNotificationCenter.DefaultCenter.AddObserver ("UIApplicationWillResignActiveNotification", ApplicationWillResignActive); NSNotificationCenter.DefaultCenter.AddObserver ("UIApplicationWillTerminateNotification", ApplicationWillResignActive); NSNotificationCenter.DefaultCenter.AddObserver ("UIApplicationWillEnterForegroundNotification", ApplicationWillReturnActive); ViewBackground.Layer.CornerRadius = 10.0f; NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Action, delegate { if(string.IsNullOrEmpty(image)) return; var shareText = "#PuppyKittyOverflow Adorable Animals: " + image; var social = new UIActivityViewController(new NSObject[] { new NSString(shareText)}, new UIActivity[] { new UIActivity() }); PresentViewController(social, true, null); }); // Perform any additional setup after loading the view, typically from a nib. }
public override string GetSubjectForActivity(UIActivityViewController activityViewController, Foundation.NSString activityType) { return _subject; }
private void Actionbutton_Clicked(object sender, EventArgs e) { this.Player.Pause(); var alert = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet); alert.AddAction((UIAlertAction.Create("Save Video", UIAlertActionStyle.Default, async(UIAlertAction obj) => { SaveToAlbum(local, "nidal", namefile); }))); alert.AddAction((UIAlertAction.Create("Share", UIAlertActionStyle.Default, (UIAlertAction obj) => { var ii = NSUrl.FromFilename(local); var imageToShare = ii.Copy(); var activityItems = new NSObject[] { imageToShare }; var controller = new UIActivityViewController(activityItems, null); this.PresentViewController(controller, true, null); }))); alert.AddAction((UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, (UIAlertAction obj) => { try { local cal = new local(); // Images mig =new Images () cal.remove(this.Title); img.imG.ViewDidLoad(); } catch { var armAlert = UIAlertController.Create("database dot open", string.Empty, UIAlertControllerStyle.Alert); var cancelAction1 = UIAlertAction.Create("ok", UIAlertActionStyle.Cancel, alertAction1 => { }); armAlert.AddAction(cancelAction1); PresentViewController(armAlert, true, null); } NavigationController.PopViewController(true); }))); alert.AddAction((UIAlertAction.Create("Rename", UIAlertActionStyle.Default, (UIAlertAction obj) => { UITextField field = new UITextField(); //field.Text = this.Title; var frame = new CGRect(40, 40, 300, 60); var messbox = UIAlertController.Create("Change a Name", string.Empty, UIAlertControllerStyle.Alert); messbox.View.BackgroundColor = UIColor.DarkGray; // UITextField field = null; // UITextField field2 = null; messbox.AddTextField((textField) => { // field = textField; // Initialize field // field.Placeholder = placeholder; // field.Placeholder = library.Messages(0); // field.BackgroundColor = UIColor.Yellow; // field.Layer.BorderColor = UIColor.Gray.CGColor; // field.Font = library.Font(); field = textField; field.Frame = frame; field.Layer.BorderWidth = 0; // field.Layer.CornerRadius = 20; // field = new UITextField(new CoreGraphics.CGRect(10, 60, 300, 60)); // field.SecureTextEntry = true; }); var cancelAction = UIAlertAction.Create(library.StrForm(4), UIAlertActionStyle.Cancel, alertAction => { }); var okayAction = UIAlertAction.Create(library.StrForm(3), UIAlertActionStyle.Default, alertAction => { string[] data = new string[] { field.Text + ".mp4", this.Title }; this.Title = field.Text + ".mp4"; local cal = new local(); // Images mig =new Images () cal.Uplod(data); img.imG.ViewDidLoad(); cal.retUIbutton(); }); messbox.AddAction(cancelAction); messbox.AddAction(okayAction); //Present Alert PresentViewController(messbox, true, null); }))); alert.AddAction((UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) => { }))); this.PresentViewController(alert, true, null); }
/// <summary> /// Share a message with compatible services /// </summary> /// <param name="message">Message to share</param> /// <param name="options">Platform specific options</param> /// <param name="excludedActivityTypes">UIActivityTypes that should not be displayed</param> /// <returns>True if the operation was successful, false otherwise</returns> private async Task <bool> Share(ShareMessage message, ShareOptions options = null, params NSString[] excludedActivityTypes) { if (message == null) { throw new ArgumentNullException(nameof(message)); } try { // create activity items var items = new List <NSObject>(); if (message.Text != null) { items.Add(new ShareActivityItemSource(new NSString(message.Text), message.Title)); } if (message.Url != null) { items.Add(new ShareActivityItemSource(NSUrl.FromString(message.Url), message.Title)); } // create activity controller var activityController = new UIActivityViewController(items.ToArray(), null); // set excluded activity types if (excludedActivityTypes == null) { // use ShareOptions.ExcludedUIActivityTypes excludedActivityTypes = options?.ExcludedUIActivityTypes?.Select(x => GetUIActivityType(x)).Where(x => x != null).ToArray(); } if (excludedActivityTypes == null) { // use ShareImplementation.ExcludedUIActivityTypes excludedActivityTypes = ExcludedUIActivityTypes?.ToArray(); } if (excludedActivityTypes != null && excludedActivityTypes.Length > 0) { activityController.ExcludedActivityTypes = excludedActivityTypes; } // show activity controller var vc = GetVisibleViewController(); if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = vc.View; var rect = options?.PopoverAnchorRectangle; if (rect != null) { activityController.PopoverPresentationController.SourceRect = new CGRect(rect.X, rect.Y, rect.Width, rect.Height); } } } await vc.PresentViewControllerAsync(activityController, true); return(true); } catch (Exception ex) { Console.WriteLine("Unable to share: " + ex.Message); return(false); } }