How To Register Classes Online Fayetteville Tech
Update annotation: Owen Fifty Brown updated this tutorial for Xcode x.1, Swift 4.2, and iOS 12. Andy Pereira wrote the original.
A lot of developers want to exist able to share their app data via email, Messages or AirDrop. Sharing is a user-friendly style for users to ship data to each other or betwixt devices. Information technology may even net you some new customers!
Fortunately, since iOS 6, Apple has provided the handy, but much-overlooked, UIActivityViewController class, which offers a make clean interface for sharing and manipulating data inside your app.
Yous'll larn everything you demand to know to use this class in this UIActivityViewController tutorial!
To set up sharing inside your app, y'all'll have to configure some keys inside your app's Info.plist and handle a few system callbacks within your app's AppDelegate. One time set upwards, iOS can open your app with the URL pointing to the information to import or export.
Set for some book sharing fun? Read on.
Getting Started
First, download the materials for this tutorial at the acme or bottom of this page using the Download Materials button. Build and run the starter project in Xcode and you'll run across the following:
Well, that's no good; there are no books to share. Here'southward how y'all can commencement sharing wonderful RW books with everyone.
UTIs and Your Plist
The get-go affair you need to exercise is gear up your Info.plist to let iOS know your app tin handle Book Tracker Documents.
To do this, you need to register your app as being able to handle certain Compatible Type Identifiers, or UTIs, exporting whatsoever UTIs that are not already known by the arrangement.
In summary, UTIs are unique identifiers that represent documents. There are UTIs already built into iOS for handling common document types such every bit public.jpeg or public.html.
Defining Your UTIs
You're going to register your app to handle documents with the com.raywenderlich.BookTracker.btkr UTI representing the description of a book.
Yous'll give iOS information about the UTI, such as what file name extension it uses, what mime type it's encoded every bit when sharing and, finally, the file'southward icon.
So now it's fourth dimension to see it in action! Open Info.plist and add the following entries under the Information Property List cardinal:
You tin can read up on what each of these values hateful in Apple tree's UTI guide, but here are the important things to note:
- The Document types entry defines what UTIs your app supports — in your case, the com.raywenderlich.BookTracker.btkr UTI, as an Owner/Editor.
- Document types is also where y'all set the names of the icons that iOS should utilise when displaying your file type. You'll demand to make sure you have an icon for each of the sizes listed in the plist.
- The Exported Type UTIs entry gives some information about com.raywenderlich.BookTracker.btkr, since it isn't a public UTI. Here you define that your app can handle files ending in .btkr or files that have a mime type of application/booktracker.
Importing Your First Book
Believe it or not, past setting these keys, you lot have told iOS to offset sending your app files that end with the .btkr extension.
Y'all tin examination this out by emailing yourself a copy of the Swift Amateur.btkr file from the Download Materials resource. Delight brand sure you unzip the file earlier emailing it to yourself. Otherwise, both the file extension UTI and mime type will be wrong.
You tin can tap on the attachment and it will prompt you lot to open up the book in the Volume Tracker app. Selecting Book Tracker volition open up the app. However, it won't load the data from the sample file because you haven't implemented the code for that even so.
Now that yous're a UTI wizard, it'south fourth dimension for you to sprinkle some magic.
Note: If you don't come across "Copy to Book Tracker" displayed in UIActivityViewController later tapping the fastened file in your email, y'all may need to edit the gild of supported apps by scrolling to the end of the list, selecting More than, and moving "Re-create to BookTracker" to the top of the list.
Importing App Information
Before you tin handle opening data from the file, you'll need some code that can work with the file that y'all accept passed to information technology.
Add that code by opening Volume.swift, and replacing importData(from:) with the post-obit:
static func importData(from url: URL) { // 1 guard let data = try? Data(contentsOf: url), allow book = try? JSONDecoder().decode(Book.self, from: data) else { return } // two BookManager.shared.add together(book: book) // 3 attempt? FileManager.default.removeItem(at: url) } Hither'southward a step-by-stride explanation of the lawmaking in a higher place:
- Verify the app tin read the contents of the URL provided to information technology. Create a new
Volumeobject with information from the URL. - Add together the new book to your app's information.
- Finally, delete the certificate that iOS saved to your app'south sandbox after opening it.
Notation: If you don't delete these files as they come up in, your app will continue to abound in size with no manner for the user to articulate the app's information — except… past deleting your app!
Next, when an external app wants to send your app a file, iOS will invoke application(_:open:options:) to permit your app to accept the file. Open AppDelegate.swift and add together the following code:
func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:] ) -> Bool { // 1 baby-sit url.pathExtension == "btkr" else { render false } // ii Book.importData(from: url) // iii guard permit navigationController = window?.rootViewController as? UINavigationController, permit bookTableViewController = navigationController.viewControllers .first as? BooksTableViewController else { return true } // 4 bookTableViewController.tableView.reloadData() render true } Here's a footstep-by-step explanation of the code higher up:
- Verify the URL'due south extension is btkr, since your app merely supports files with that extension.
- Use the
staticmethod onBookyou added above to import the data into your app. - Verify the root view controller is an instance of a
UINavigationControllerand that its showtime view controller is an instance ofBooksTableViewController. - Reload
BooksTableViewController'due south tabular array view to show the newly imported book, so returntrueto inform iOS that your app successfully processed the provided volume information.
Note: The method still returns true even if the view controller hierarchy was not prepare correctly. This works because your app has, in fact, processed the provided book information in footstep 2 above.
Build and run your app. If all works well, you should be able to open up the e-mail attachment and encounter the book imported into your app as shown below.
Exporting App Data
So far in this UIActivityViewController tutorial, you've added functionality to your app that handles importing data from other apps. However, what if yous desire to share your app'south data?
You're in luck, as Apple has made exporting data nice and like shooting fish in a barrel.
Your app will demand code to handle exporting your favorite books. Open Book.swift and supervene upon the existing exportToURL() definition with the following:
func exportToURL() -> URL? { // 1 baby-sit allow encoded = attempt? JSONEncoder().encode(self) else { render goose egg } // two allow documents = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask ).showtime guard let path = documents?.appendingPathComponent("/\(proper noun).btkr") else { return nil } // three do { try encoded.write(to: path, options: .atomicWrite) return path } catch { print(fault.localizedDescription) return zero } } Here's a step-by-footstep explanation of the code above:
- Encode
Volumeas JSON. - Verify that your app can admission its Documents directory without error.
- Finally, salvage the data to your Documents directory and return the URL of the newly-created file.
Now that you can consign Volume data to a file, you're going to demand an piece of cake style to share that data. Open up BookDetailViewController.swift and supervene upon the implementation of share(_:) with the post-obit:
@IBAction func share(_ sender: UIBarButtonItem) { // Get latest changes saveBook() // 1 guard let detailBook = detailBook, permit url = detailBook.exportToURL() else { return } // ii permit activity = UIActivityViewController( activityItems: ["Check out this book! I similar using Book Tracker.", url], applicationActivities: nil ) action.popoverPresentationController?.barButtonItem = sender // iii present(activity, animated: true, completion: nada) } Hither's a step-by-stride explanation of the lawmaking above:
- Ferify that y'all have a detail book and that you can think the URL from
exportToURL(). - Create an case of
UIActivityViewControllerand, foractivityItems, pass in a message and the URL to your app'due south data file. Depending on the action the user selects from the activeness menu, iOS uses the message y'all pass in to pre-populate its content. For case, if the user chooses to share the book via Email, the bulletin you passed in will pre-populate the body of the email. Since not all activities have such adequacy, such as AirDrop, iOS may discard the message.UIActivityViewControllerwill practice all of this heavy lifting for you and, since you divers all of the required information in your Info.plist, it'll know just what to practise with it. - Present the
UIActivityViewControllerto the user.
Build and run your app, open a book and endeavor to share it. You'll discover that y'all run into a few options available to you as shown below:
UIActivityViewController has been around since iOS6, just despite how useful it is, it's oft under-appreciated. Perhaps ane of the all-time options is the ability to AirDrop. If you have 2 devices — or better withal, a friend with the Book Tracker app installed — yous can exam AirDropping books!
Where to Go From Hither?
You tin download the completed version of the projection using the Download Materials button at the top or bottom of this tutorial.
At present that you know how iOS imports and exports app data, you're ready to take this noesis and showtime sharing your favorite books or any other data of your option.
Here are some resources for farther study:
- A video on the same topic from WWDC17: Extend Your App'due south Presence With Sharing.
- Another tutorial that leverages
UIActivityViewController: Requesting App Ratings and Reviews Tutorial for iOS. - If you're interested to know how to brand your app show up equally an choice within
UIActivityViewController, you may want to watch iOS App Extensions video tutorial series.
Source: https://www.raywenderlich.com/813044-uiactivityviewcontroller-tutorial-sharing-data
Posted by: smithbrose1970.blogspot.com

0 Response to "How To Register Classes Online Fayetteville Tech"
Post a Comment