http://www.appcoda.com/ios7-airdrop-programming-tutorial/

Adding AirDrop File Sharing Feature to Your iOS Apps

october 30, 2013 by simon ng 12 comments

AirDrop is Apple’s answer to file and data sharing. Before the debut of iOS 7, users need to rely on 3rd-party apps such as Bump to share files between iOS devices. In iOS 7, Apple introduced a new feature called AirDrop to all iPhone 5 models, the fourth-generation iPad, the iPad mini, and fifth-generation iPod touch models. With AirDrop, you can easily share data with other nearby iOS devices. In brief, the feature allows you to share photos, videos, contacts, URLs, Passbook passes, app listings on the App Store, media listings on iTunes Store, location in Maps, etc.

As a developer, wouldn’t be great to incorporate the AirDrop feature in your app? So your users can easily share photos, text file or any types of document easily with nearby devices. The UIActivityViewController class bundled in the iOS 7 SDK makes it simple for developers to integrate AirDrop feature in their apps. The class shields you from the underlying details of file sharing. What you just need is tell the class the objects you want to share and it handles the rest. In this tutorial, we’ll demonstrate the usage of UIActivityViewController and see how you can use it to share images / documents by using AirDrop.

Let’s get started.

AirDrop Overview

Before we step into the implementation, let’s have a quick look at AirDrop. It’s very simple to use AirDrop. Simply bring up Control Center and tap AirDrop to enable it. You can either select “Contact Only” or “Everyone” depending on whom you want to share the data with. If you choose the Contact Only option, your device will only discovered by people listed in your contacts. Obviously, your device can be discovered by anyone for the Everyone option.

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, allowing for faster data transmission. It doesn’t mean you need to connect the devices to a Wi-Fi network in order to use AirDrop. Your WiFi simply needs to be on for the data transfer.

Say you want to share a photo in the Photos app from one iPhone to another. Assuming you’ve enabled AirDrop on both devices, to share the photos with another device, tap the Share button (the one with an arrow pointing up) at the lower-left of the screen.

In the AirDrop area, you should see the name of the devices that are eligible for sharing. AirDrop is not available when the screen is turned off. So make sure the device on the receiving side is switched on. You can then select the device to share the photo. On the other device, you’ll see a preview of the photo and a confirmation request. The recipient can accept or decline to receive the image. If you choose the accept option, the photo is then transferred and automatically saved in the camera roll.

AirDrop doesn’t just work with the Photos app. You can also find the share option in most of the built-in apps such as Contacts, iTunes, App Store, Safari, to name a few. If you’re new to AirDrop, you should now have a better idea.

Let’s move on and see how we can incorporate AirDrop feature in your app to share various types of data.

A Quick Look at UIActivityViewController

You may think it’ll take a lot of efforts to implement the AirDrop feature. Conversely, you just need a few lines of code to add AirDrop support. The UIActivityViewController class available in iOS 7 SDK makes it super easy to integrate the feature. The AirDrop has been built into the class.

The UIActivityViewController class is a standard view controller that provides several standard services, such as copying items to the clipboard, sharing content to social media sites, sending items via Messages, etc. In iOS 7 SDK, the class comes with the AirDrop feature built-in.

Say, you have an array of objects to share using AirDrop. All you need to do is to initiate a UIActivityViewController with the array of objects and present it on screen:

1
2
UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];

With just two lines of code, you can bring up the activity view with AirDrop option. Whenever there is a nearby device detected, the activity controller automatically shows the device and handles the data transfer if you choose to.

Optionally, you can exclude certain types of activities. Say, you can just display the AirDrop activity by excluding all other activities. Use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
    UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    
    NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
                                    UIActivityTypePostToWeibo,
                                    UIActivityTypeMessage, UIActivityTypeMail,
                                    UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                    UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
                                    UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                    UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
    controller.excludedActivityTypes = excludedActivities;
    
    [self presentViewController:controller animated:YES completion:nil];

The activity view controller now only shows the AirDrop option:

You can use UIActivityViewController to share different types of data including NSString, UIImage and NSURL. Not only you can use NSURL to share a link, it allows developers to transfer any types of files by using file URL.

On the receiving side, when the other device receives the data, it’ll automatically open an app based on the data type. Say, if an UIImage is transferred, the received image will be displayed in Photos app. When you transfer a PDF file, the other device will open it in Safari. If you just share a NSString object, the data will be presented in Notes app.

A Glance at the AirDrop Demo App

To give you a better idea about UIActivityViewController and AirDrop, we’ll build a AirDrop demo app. The app is very simple. When it is first launched, you’ll see a table view listing a few files including an image file, a PDF file and a text file. You can tap the file and view the content. In the content view, there is an action button on the top-right corner of screen. Tapping it will bring up the AirDrop option and you can share the image or document with nearby device.

You’re encouraged to build the demo app from scratch. But to save your time, you can download this project template to start with. When you open Xcode project, you should find the following Storyboard:

I have already implemented the ListTableViewController and DocumentViewController for you. If you compile and run the app, you’ll be presented with a list of files. When you tap any of the file, the image or document content will be displayed. But the share button is not yet implemented and that is what we’re going to talk about.

Adding AirDrop Feature

In the project template, the ListTableViewController is used to displayed the list of files in a table view, while the DocumentViewController presents the document content via a web view. The action button in the document view is associated with the share: method of the DocumentViewController class. Edit the method with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (IBAction)share:(id)sender {
    NSURL *url = [self fileToURL:self.documentName];
    NSArray *objectsToShare = @[url];

UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    
    // Exclude all activities except AirDrop.
    NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
                                    UIActivityTypePostToWeibo,
                                    UIActivityTypeMessage, UIActivityTypeMail,
                                    UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                    UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
                                    UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                    UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
    controller.excludedActivityTypes = excludedActivities;
    
    // Present the controller
    [self presentViewController:controller animated:YES completion:nil];

}

If you’re not forgetful, the above code should be very familiar to you as we’ve discussed it at the very beginning. The above code simply creates a UIActivityViewController, excludes all activities except AirDrop and presents the controller as a modal view. The tricky part is how you define the objects to share. Here we turn the file to share into a NSURL object and pass the file URL as an array to AirDrop.

The first two lines of code are responsible for the file URL conversion. The documentName property stores the current file (e.g. ios-game-kit-sample.pdf) displaying in document view. We simply call up the fileToURL: method with the document name and it returns the corresponding file URL. The fileToURL: method is bundled in the project template and here is the code:

1
2
3
4
5
6
7
- (NSURL *) fileToURL:(NSString*)filename
{
    NSArray *fileComponents = [filename componentsSeparatedByString:@"."];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:[fileComponents objectAtIndex:0] ofType:[fileComponents objectAtIndex:1]];

return [NSURL fileURLWithPath:filePath];
}

The code is very straightforward. For example, the ios-game-kit-sample.pdf will be transformed to file:///Users/simon/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A5321493-318A-4A3B-8B37-E56B8B4405FC/AirDropDemo.app/ios-game-kit-sample.pdf. The file URL varies depending on the device you’re running. But the URL should begin with the “file://” protocol. With the file URL object, we create the corresponding array and pass it to UIActivityViewController for AirDrop sharing.

Build and Run the AirDrop Demo

You’re done. That’s what you need to implement AirDrop sharing. Compile and run the app on a real iPhone. Yes, you need a real device to test AirDrop sharing. The sharing feature won’t work on the Simulator.

Uniform Type Identifiers (UTIs)

When you share an image to another iOS device, the receiving side automatically opens Photos app and loads the image. If you transfer a PDF file, the receiving device may prompt you to pick an app for opening the file or open it directly in iBooks. How can iOS know which app to use for the type of data?

UTIs (short for Uniform Type Identifiers) is Apple’s answer to identify data handled within the system. In brief, a uniform type identifier is a unique identifier for a particular type of data or file. For instance, com.adobe.pdf represents a PDF document and public.png represents a PNG image. You can find the full list of registered UTIs here. Application that is capable of opening a specific type of file has registered to handle that UTI with the iOS. So whenever that type of file is opened, iOS hands off that file to the specific app.

The system allows multiple apps to register the same UTI. In this case, iOS will prompt user with the list of capable apps for opening the file. For example, when you share a PDF document, you may experience the following screen in the receiving device:

Wrap Up

AirDrop is a very cool feature introduced in iOS 7. It offers a great way to share data between devices. Best of all, the built-in UIActivityViewController has made it easy for developers to add AirDrop support in their apps. As you can see from the demo app, it just needs a few lines of code to implement the feature. I highly recommend you to put this sharing feature in your app.

For your complete reference, you can download the full source code of the Xcode project from here.

As always, leave us comment and share your thought about the tutorial. We love to hear your feedback.

Adding AirDrop File Sharing Feature to Your iOS Apps的更多相关文章

  1. RH253读书笔记(5)-Lab 5 Network File Sharing Services

    Lab 5 Network File Sharing Services Goal: Share file or printer resources with FTP, NFS and Samba Se ...

  2. Another option for file sharing(转)

    原文地址  https://security.googleblog.com/2017/02/another-option-for-file-sharing.html Another option fo ...

  3. Delphi 10.3.1 Secure File Sharing解决应用间文件共享

    Delphi 10.3.1 为Android项目提供了Secure File Sharing选择项,默认是False.这一项是设置什么呢? 原来,Android 7及以后的版本,为了加强OS的安全性, ...

  4. HDU 3269 P2P File Sharing System(模拟)(2009 Asia Ningbo Regional Contest)

    Problem Description Peer-to-peer(P2P) computing technology has been widely used on the Internet to e ...

  5. Differences Between Xcode Project Templates for iOS Apps

    Differences Between Xcode Project Templates for iOS Apps When you create a new iOS app project in Xc ...

  6. Start Developing iOS Apps Today

    view types - view常见类型

  7. 《Start Developing iOS Apps Today》摘抄

    原文:<Start Developing iOS Apps Today> Review the Source Code 入口函数main.m #import <UIKit/UIKit ...

  8. ComponentOne Xuni助力Xamarin开发者突破百万,快速开发Android、IOS Apps

    在微软Build 2015上,随着VS 2015的预览版发布,Xamrine免费版已经作为VS 2015跨平台移动解决方案的核心.与此同时,Xamarin官方也宣布其用户量达到百万之多.2011年7月 ...

  9. Table View Programming Guide for iOS---(一)---About Table Views in iOS Apps

    About Table Views in iOS Apps Table views are versatile user interface objects frequently found in i ...

随机推荐

  1. FM/PCM与FM/PPM的区别

    FM/PCM的优点:     1 高可靠性和高抗干扰性.大家知道,一般PPM遥控设备都要求在操作时先开发射机后开接收机,先关接收机后关发射机.其原因是在没有发射信号时,接受机会因自身内部的噪音或外界的 ...

  2. 【学】CSS3的3D动画 ——3D旋转之骰子样式的钟表(2)上

    这个是3D旋转的进阶版,是一个类似与骰子的正方体.这个版本只有秒数的个位数,还没有写整个钟表,下面那个版本好好想想该怎么写 这个效果需要用到transform-style: preserve-3d. ...

  3. 闲谈Tomcat性能优化

    Tomcat在各位JavaWeb从业者常常就是默认的开发环境,但是Tomcat的默认配置作为生产环境,尤其是内存和线程的配置,默认都很低,容易成为性能瓶颈. 幸好Tomcat还有很多的提升空间.下文介 ...

  4. 一行代码解释.net事件与委托

    button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); }; delegat ...

  5. .NET 环境中使用RabbitMQ(转)

    在企业应用系统领域,会面对不同系统之间的通信.集成与整合,尤其当面临异构系统时,这种分布式的调用与通信变得越发重要.其次,系统中一般会有很多对实时性要求不高的但是执行起来比较较耗时的地方,比如发送短信 ...

  6. 课堂笔记--Strom并发模型

    Strom并发模型:     topology是如何运行的?(可与mapreduce对比)         第一层:cluster         第二层:supervisor(host.node.机 ...

  7. Thinkpad 笔记本VMware Workstation 安装虚拟机出现“此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态”解决方法

        今天在使用VMware打算在机器中安装新的虚拟机时,出现"此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态"错误如下:  提示信息: 已将该虚拟机配 ...

  8. DataSet读取XML

    string file = File.ReadAllText("c://123.xml", Encoding.Default); using (DataSet ds = new D ...

  9. ie6并不是不支持!important

    之前对ie6接触不多,并且认识也不深,虽然知道ie6中的!important很特别,但是并没有记住特别在哪里~今天就记录一下吧! 首先,很多人说ie6是不支持!important的,其实这个一个错误的 ...

  10. “REST”——Representational State Transfer(表述性状态转移)

    Representational State Transfer http://www.infoq.com/cn/articles/understanding-restful-style/#anch10 ...