قالب وردپرس درنا توس
Home / IOS Development / UIActivityViewController Tutorial: Data Sharing | raywenderlich.com

UIActivityViewController Tutorial: Data Sharing | raywenderlich.com



Update Note : Owen L Brown updated this tutorial for Xcode 10.1, Swift 4.2 and iOS 12. Andy Pereira wrote the original.

Many developers will be able to share their app data via email, Messaging or AirDrop. Sharing is a convenient way for users to send data to each other or between devices. It can even cost you some new customers!

Fortunately, since iOS 6 has Apple provided the practical, but much overlooked translation UIActivityViewController that provides a clean interface for sharing and manipulating data in your app.

You learn everything you need to know to use this class in this guide UIActivityViewController !

To configure sharing in your app, you need to configure some keys in the app's Info.plist and handle some system recalls in the app AppDelegate . Once created, iOS can open your app with the URL pointing to the data to be imported or exported.

Ready for some sharing of books? Read on.

Getting Started

First download the materials for this tutorial at the top or bottom of this page using the Download Materials button . Build and run the startup project in Xcode and you will see the following:

 IActivityViewController training empty books screen

Well, that's not good; There are no books to share. Here's how to start sharing amazing RW books with everyone.

UTIs and Plist

The first thing to do is set up Info.plist to let iOS know that your app can handle Book Tracker Documents .

To do this, you need to register your app as being able to handle certain Uniform Type Identifiers or UTIs, which export UTIs that are not already known to the system.

Summary, UTIs are unique identifiers representing documents. There are UTIs that are already embedded in iOS for handling common document types such as public.jpeg or public.html .

Defining UTIs

You must register your app to handle documents with com.raywenderlich.BookTracker.btkr UTI representing the description of a book.

You will provide iOS information about the UTI, such as which filename extension it uses, which mime type it is encoded as when you share it, and finally the file's icon.

So now is the time to see it in action! Open Info.plist and add the following entries under Information Property List key:

 UIActivityViewController Training Package

You can read about what each of these values ​​means in Apple's UTI guide, but here are important things to note:

  • Post Document types define which UTIs your app supports – in your case com.raywenderlich. BookTracker.btkr UTI, as owner / editor.
  • Document Types is also where you enter the names of the icons that iOS should use when displaying the file type. You need to make sure you have an icon for each of the sizes listed in the package.
  • Listing Exported Type UTIs gives some information about com.raywenderlich.BookTracker.btkr since it is not a public UTI. Here you define that your app can handle files ending in .btkr or files that have a mime-type application / booktracker

    .

Import your first book

Believe it or not by putting these keys, you have told iOS to start sending app files ending with the extension .btkr .

You can test this by sending you a copy of Swift Apprentice.btkr file from Download materials resource. Make sure you unzip the file before sending it to yourself. Otherwise, both the UTI and the mime type will be incorrect.

 UIActivityViewController training email box attachment

You can tap the attachment and it will ask you to open the book in the Book Tracker app. If you choose Book Tracker, the app opens. However, it will not load the data from the sample file because you have not yet implemented the code for it.

Now that you're a UTI wizard, it's time to splash some magic.

Note : If you do not see "Copy to Book Tracking" shown in UIActivityViewController after tapping the attached file in your email, you may need to edit the order of supported apps by scrolling to the end of list, select More and move "Copy to BookTracker" to the top of the list.

Importing app data

Before you can handle opening data from the file, you must have code that can work with the file you passed to it.

Add the code by opening Book.swift and replacing importData (from :) with the following:

  static func importData (from URL: URL) {
// 1
guard
let data = try? Data (contentOf: url),
let the book = try? JSONDecoder (). Decode (Book.self, from: data)
otherwise {return}

// 2
BookManager.shared.add (book: book)

// 3
try? FileManager.default.removeItem (on: url)
}

Here is a step by step explanation of the code above:

  1. Confirm that the app can read the contents of the URL given to it. Create a new book object with data from the URL.
  2. Add the new book to the app's data.
  3. Finally, delete the document that iOS stored in the app's sandbox after opening it.

] Note : If you do not delete these files as they enter, your app continues to grow in size, but the user cannot clear the app's data – except … by delete your app!

When an external app wants to send your app a file, iOS will invoke application (_: open: options :) to allow your app to accept the file. Open AppDelegate.swift and add the following code:

  func application (
_ app: UIApplication,
open URL: URL options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
// 1
watch url.pathExtension == "btkr" otherwise {return false}

// 2
Book.importData (from: url)

// 3
guard
la navigationController = window? .rootViewController som? UINavigationController,
leave bookTableViewController = navigationController.viewControllers
first as? Book Stable View Controller
otherwise {return true}

// 4
bookTableViewController.tableView.reloadData ()
return true
}

Here's a step by step explanation of the above code:

  1. Verify the URL extension is btkr since your app only supports files with that extension.
  2. Use static method on book you added above to import the data into your app.
  3. Confirm the rotation display control is an instance of a UINavigationController and that the first display controller is an instance of BooksTableViewController .
  4. Update BooksTableViewController its table view to display the newly imported book, and then return true to inform iOS that your app successfully processed the specified book information.

Note : The method still returns true even though the display regulator hierarchy was not properly configured. This works because your app has actually processed the specified book information in step two above.

Build and run your app. If everything works well, you should be able to open the email attachment and see the book imported to your app as shown below.

 UIActivityViewController Imported Book Training List

Exporting app data

So far in this guide UIActivityViewController you have added functionality to your app that handles import of data from other apps . But what if you want to share the app's data?

You have happiness when Apple has done export data smoothly and easily.

Your app needs code to handle the export of your favorite books. Open Book.swift and replace the existing exportToURL () definition with the following:

  func exportToURL () -> URL? {
// 1
guard let coded = try? JSONEncoder (). Code (self) other {return nil}

// 2
leave documents = FileManager.default.urls (
for: .documentDirectory,
in: .userDomainMask
).first

guard leave path = documents? .appendingPathComponent ("/ (name) .btkr") other {
return zero
}

// 3
do {
try encoded.write (to: path, alternatives: .atomicWrite)
return path
} catch {
print (error.localizedDescription)
return zero
}
}

Here is a step-by-step explanation of the above code:

  1. Code Order as JSON.
  2. Confirm that your app can access its directory Documents without error
  3. Finally, save the data in the directory Documents and return the URL of the newly created file.

Now that you can export Book data to a file, you need an easy way to share the data. Open BookDetailViewController.swift and replace the implementation of parts (_ :) with the following:

  @IBAction func share (_ sender: UIBarButtonItem) {
// Get the latest changes
saveBook ()

// 1
guard
let detailBook = retail book,
la url = detailBook.exportToURL ()
otherwise {return}

// 2
leave activity = UIActivityViewController (
activityItems: ["Check out this book! I like using Book Tracker.", url],
applicationActivities: null
)
activity.popoverPresentationController? .barButtonItem = sender

// 3
current (activity, animated: true, completion: null)
}

Here is a step-by-step explanation of the above code:

  1. Confirm that you have a retail book and that you can retrieve the URL from exportToURL () .
  2. Create an instance of UIActivityViewController and for activityItems submit a message and the URL of the app's data file. Depending on the activity the user selects from the activity menu, the iOS uses the message you submit to pre-fill the content. For example, if the user chooses to share the book by email, the message you submitted will pre-fill the email body. Since not all activities have such an opportunity, such as AirDrop, iOS can discard the message. UIActivityViewController will do all this heavy lifting for you, and since you defined all the necessary information in Info.plist it only knows what to do with it. 19659023] Present UIActivityViewController to the user.

Build and run your app, open a book and try to share it. You see that you see some options available to you as shown below:

 UIActivityViewController Training Booklet

UIActivityViewController has existed since iOS6, but despite how useful it is, are often undervalued. Perhaps one of the best options is the ability of AirDrop. If you have two devices – or better yet, a friend with the Book Tracker app installed – you can test AirDropping books!

Where do you go from here?

You can download the completed version of the project using Download the materials button at the top or bottom of this tutorial.

Now that you know how iOS imports and exports app data, you're ready to take this knowledge and start sharing your favorite books or other data about your choice.

Here are some resources for further studies:


Source link