Airdrop Tutorial in iOS8 with Swift

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 for iOS8 with Xcode 6.3.1.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftAirdropTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

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". Hold down the Ctrl key and select both the Image View and the Share Button. Press 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() {
    var image : UIImage = UIImage(named:"imac.jpg")!
    imageView.image = image

Implement the shareImage method

@IBAction func shareImage(sender: AnyObject) {
    let image = imageView.image!
    let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
    controller.excludedActivityTypes = [UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypePostToFlickr, UIActivityTypePostToTencentWeibo, UIActivityTypeMail]
    self.presentViewController(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 IOS8SwiftAirdropTutorial at the ioscreator repository on Github.