Search code examples
swiftpdfapp-startup

Swift (4.1) how to detect if me app was open from external source


I have a application which can open a PDF file. I have this app registered as external PDF viewer. When I have a PDF file and click to share button I see my application. If I open a PDF file from external source, PDF is copied to internal application storage ".../Documents/Inbox".

How can I detect if me app was started this way? I need to detect if was, and show PDFViewController with a new PDF file.

I can read data from "Inbox" but i can't detect "application startup type". And how can I detect a new pdf file? Order by date of creation and get first?

AppDelegate:

func applicationWillEnterForeground(_ application: UIApplication) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "openPdfFromExternalSource"), object: nil)
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

and in PDFViewController I have:

    override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.ShowPdfFile), name: NSNotification.Name(rawValue: "openPdfFromExternalSource"), object: nil)
}

Solution

  • i found it. "application(_:open:options:)" is called always (when app is on backgound) and i can open a pdf file from shared option.

    application(_ app: UIApplication, 
                     open url: URL, 
                  options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
    

    url param contains path to a pdf file. For more information see https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623112-application