Send Files through AirDrop using Xamarin.iOS

Sending Files

AirDrop has been baked into the UIActivityViewController. All that’s needed to send a file via AirDrop is to pass it in as an item in a NSObject Array to the first parameter of the UIActivityViewController.

In the following example we create an UIImageView that takes up the entire screen. A button is also added to the view. On the click event of the button we present a new UIActivityViewController, whose constructor has a one item NSObject array that contains the UIImageViews Image.

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

            var bounds = UIScreen.MainScreen.Bounds;

            //Initialize ImageView and set it as a 'background'
            _imageView = new UIImageView(bounds) {Image = UIImage.FromFile("IMG_5398.JPG")};
            _imageView.Image.Scale(bounds.Size);
            Add(_imageView);

            _button = UIButton.FromType(UIButtonType.RoundedRect);

            //Place button in the middle
            _button.Frame = new RectangleF(
                View.Frame.Width / 2 - ButtonWidth / 2,
                View.Frame.Height / 2 - ButtonHeight / 2,
                ButtonWidth,
                ButtonHeight);
            _button.BackgroundColor = UIColor.White;

            _button.SetTitle("Click me", UIControlState.Normal);

            _button.TouchUpInside += (sender, e) =>
            {
                //This constructor will give us the option to share the _imageView.Image via AirDrop
                var a = new UIActivityViewController(new NSObject[] { _imageView.Image }, null);
                PresentViewController(a, true, null);
            };

            _button.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin |
                UIViewAutoresizing.FlexibleBottomMargin;

            View.AddSubview(_button);
        }

That’s it! The source code to the recipe is available on GitHub.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s