3

When you open url that contain PDF file safari ask you if you want to open it on safari or in iBook.

I want to do the same thing , in my project i had a collection view contains videos and photos, i want the user to chose if he want to open the file on the app or to open it with other media player.

2
  • its totally different , i what to know how to do it in swift Commented Jul 24, 2016 at 7:15
  • @EvgeniyMishustin The duplicated question is Android, this is iOS, it most definitely has nothing to do with it Commented Jul 25, 2016 at 9:35

2 Answers 2

7

For loading into your own app it depends on which class you're using to display content on the exact code you'd use but for opening in another app you'd normally use a share button. Here is example code that will work if you wire up the @IBAction and @IBOutlet to the same bar button in your UI (and place a file at the fileURL that you specify):

import UIKit
class ViewController: UIViewController {

    // UIDocumentInteractionController instance is a class property
    var docController:UIDocumentInteractionController!
    @IBOutlet weak var shareButton: UIBarButtonItem!
    // called when bar button item is pressed
    @IBAction func shareDoc(sender: AnyObject) {
        // present UIDocumentInteractionController
        if let barButton = sender as? UIBarButtonItem {
            docController.presentOptionsMenuFromBarButtonItem(barButton, animated: true)
        }
        else {
            print("Wrong button type, check that it is a UIBarButton")
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // retrieve URL to file in main bundle
        if let fileURL = NSBundle.mainBundle().URLForResource("MyImage", withExtension: "jpg") {
            // Instantiate the interaction controller
            self.docController = UIDocumentInteractionController(URL: fileURL)
        }
        else {
            shareButton.enabled = false
            print("File missing! Button has been disabled")
        }
    }

}

Notes

A UIDocumentInteractionController is used to enable the sharing of documents between your app and other apps installed on a user's device. It is simple to set up as long as you remember three rules:

  1. Always make the UIDocumentInteractionController instance a class (type) property. If you only retain a reference to the controller for the life of the method that is triggered by the button press your app will crash.

  2. Configure the UIDocumentInteractionController before the button calling the method is pressed so that there is not a wait in which the app is waiting for the popover to appear. This is important because while the presentation of the controller happens asynchronously, the instantiation does not. And you may find that there is a noticeable delay to open the popover if you throw all the code for instantiation and presentation inside a single method called on the press of a button. (When testing you might see a delay anyway because the share button is likely going to be pressed almost straightaway but in real world use there should be more time for the controller to prepare itself and so the possibility of lag is less likely.)

  3. The third rule is that you must test this on a real device not in the simulator.

UIDocumentInteractionController Image More can be found in my blogpost on the subject.

Edit: Using a UIActivityViewController

Code for using UIActivityViewController instead of UIDocumentInteractionController

import UIKit
class ViewController: UIViewController {

    // UIDocumentInteractionController instance is a class property
    var activityController: UIActivityViewController!
    @IBOutlet weak var shareButton: UIBarButtonItem!
    // called when bar button item is pressed
    @IBAction func shareStuff(sender: AnyObject) {
        if let barButton = sender as? UIBarButtonItem {
            self.presentViewController(activityController, animated: true, completion: nil)
            let presCon = activityController.popoverPresentationController
            presCon?.barButtonItem = barButton
        }
        else {
            print("not a bar button!")
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // retrieve URL to file in main bundle
       if let img = UIImage(named:"MyImage.jpg") {
        // Instantiate the interaction controller
        activityController = UIActivityViewController(activityItems: [img], applicationActivities: nil)
        }
        else {
            shareButton.enabled = false
            print("file missing!")
        }
    }

}

You can also add custom activities to the UIActivityViewController and here is code for adding an "Open In..." button to a UIActivityViewController so that you can switch to a UIDocumentInteractionController from a UIActivityViewController.

Sign up to request clarification or add additional context in comments.

9 Comments

I would look at the interaction flow in Apple's Photos app. Where there are two ways to share an image. (1) a Select button which enables you to tick multiple images and then press a share button that appears (2) tapping on an image takes you through to a page with a share button.
Do you mean in the Photos app or in the app you are building? In Photos tap the box with the arrow pointing out of it. In your own app, you can segue to a new view controller and there display the image and a toolbar with the share option.
A toolbar is exactly what Safari provides. Alternative is to use the method that presents the controller from a rect instead.
Only way not to have a UIDocumentInteractionController or UIActivityViewController is to use a custom URL
I've added code to my answer for using UIActivityViewController. It is not an available option to open in Photos directly, only to "Save Image" or use "iCloud Photo Sharing". Be aware that currently UIDocumentInteractionController has far more apps available for opening in other apps than UIActivityViewController. The latter is largely for sharing or printing.
|
0

I did the same code for saving a PDF file from a URL (whether it's a local URL in your device storage, or it's a URL from somewhere on the internet)

Here is the Code for Swift 3 :

@IBOutlet weak var pdfWebView: UIWebView!
@IBOutlet weak var shareBtnItem: UIBarButtonItem!
var pdfURL : URL!
var docController : UIDocumentInteractionController!

then in viewDidLoad()

// retrieve URL to file in main bundle`
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("YOUR_FILE_NAME.pdf")
//Instantiate the interaction controller`
self.docController = UIDocumentInteractionController(url: fileURL)`

and in your barButtonItem tapped method (which I have called openIn(sender)):

@IBAction func openIn(_ sender: UIBarButtonItem)
 {
  // present UIDocumentInteractionController`
  docController.presentOptionsMenu(from: sender, animated: true)        
 }

FYI: You need a webView in your storyboard if you wish to show the pdf file as well

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.