Search code examples
iosswifturlstring-lengthuidocumentpickerviewcontroller

Detecting length of URL to determine the file type of UIDocumentPickerViewController


I am trying to get the file type from the documentPicker. I Allow my user to upload both PDF/WORD(doc/docx) document types and it is crucial for me to know which one it is so I can rename the file and upload to my AWS S3.

Any help appreciated, I couldn't find a way to get it directly from the UIDocumentPickerViewController.

Thus I tried to find the length of the whole URL and minus the length by 2/3 to find the first letter which is "d" or "p" then, I can set the name accordingly. However I am getting this error, Cannot invoke initializer for type 'String' with an argument list of type '(URL)'.

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        let myURL = url as URL
        print("import result : \(myURL)")

        let s3BucketName = "adnexio-directory/cv_upload"
        let url = myURL
        var remoteName = ""
        //if (url[url.length as Int - 3] == "d")
        //if (str[str.count - 3] == "d")
        if (url.length - 3 == "d")
        {
            remoteName = "IOSTEST.docx"
        }
        else if (url.length - 2 == "d")
             {
                remoteName = "IOSTEST.doc"
        }
        else
        {
            remoteName = "IOSTEST.pdf"
        }



        print("REMOTE NAME : ",remoteName)

Solution

  • The easiest way is to check the path extension of the URL

    let extension = myURL.pathExtension
    switch extension {
        case "pdf" : print("It's PDF")
        case "doc", "docx" : print("It's a MS Word document")
        default : print("It's unknown")
    }