Airdrop iOS Tutorial

In iOS 7, Apple introduced a new feature called AirDrop. With AirDrop, you can easily share data with other nearby iOS devices. AirDrop uses Bluetooth to scan for nearby devices. When a connection is established via Bluetooth, it’ll create an ad-hoc Wi-Fi network to link the two devices together. In this tutorial we will share a picture between two devices using Airdrop. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use iOSAirdropTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next

Go to the Storyboard and drag an Image View to the main View. Select the Image View and go to the Size inspector and fill in the following values.

Drag a button from the Object Library to the main view and place it beneath the Image View. Change the Title to "Share". Select the "Resolve Auto Layout" button from the bottom-right in the Storyboard and select "Reset to Suggested Constraints".

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Image View and create the following Outlet.

Ctrl and drag from the "Share" Button to the ViewController class and create the following Action.

Download the image and add it to the project. Change the viewDidLoad method to

override func viewDidLoad() {
    super.viewDidLoad()
        
    let image = UIImage(named:"imac.jpg")
    imageView.image = image
}

Implement the shareImage method

@IBAction func shareImage(_ sender: Any) {
    let image = imageView.image!
    let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
    controller.excludedActivityTypes = [.postToFacebook, .postToTwitter, .print, .copyToPasteboard,
                                            .assignToContact, .saveToCameraRoll, .mail]
        
    self.present(controller, animated: true, completion: nil)
}

The Activity Controller is a standard View Controller that displays services that your application can use. This services includes Airdrop, Mail, Post to Twitter, etc. In this tutorial only the Airdrop service will be needed, so the other services are excluded. Build and Run the project, press the share button and the Airdrop button. The image can then be transferred to another device. The iOS simulator doesn't have a Airdrop functionality, so this project should be built onto a real device.

You can download the source code of the IOSAirdropTutorial at the ioscreator repository on Github.