Search code examples
iosswiftguard

How does throw declare throughs 'startAccessingSecurityScopedResource()' in Swift?


I'd import data through the current file selector. I'm looking at the development document and following it, and there's one problem. I'm about to get an error when I'm not in the condition statement of the guard, but 'throw' is not available. How can you solve this problem?

func startAccessingSecurityScopedResource() -> Bool

Usage

    func presentDocument(at documentURL: URL) {


        // Start accessing a security-scoped resource.
        guard documentURL.startAccessingSecurityScopedResource() else {
            throw IXError.fileAcessFailed // Error is not handled because the enclosing function is not declared 'throws'
            return
        }

Error is not handled because the enclosing function is not declared 'throws'

I tried guard let but failed it.

        guard let Acess = documentURL.startAccessingSecurityScopedResource() else { //Initializer for conditional binding must have Optional type, not 'Bool'
            throw IXError.fileAcessFailed // Error is not handled because the enclosing function is not declared 'throws'
            return
        }

IXError

public enum IXError: Error {
    ...
}

********************************Edit start ********************************************

I added throws according to the answer, but an error occurred in the function that used it.

    func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentURLs documentURLs: [URL]) {
        guard let sourceURL = documentURLs.first else { return }
        presentDocument(at: sourceURL) // Call can throw, but it is not marked with 'try' and the error is not handled
    }
...
    func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) {
        presentDocument(at: destinationURL) // Call can throw, but it is not marked with 'try' and the error is not handled
    }
...
    func presentDocument(at documentURL: URL) throws {

        guard documentURL.startAccessingSecurityScopedResource() else {
            throw IXError.fileAcessFailed
            return
        }

Error is Call can throw, but it is not marked with 'try' and the error is not handled


Solution

  • Error is not handled because the enclosing function is not declared 'throws'

    this refers to your presentDocument function. Declare it like so:

    func presentDocument(at documentURL: URL) throws {
    ...
    }