-1

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)

2 Answers2

5

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")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
-2

I solved it. I have added the information below on how to solve this:

let str = url.absoluteString

if str[str.count - 4] == "d"
{
    remoteName = "IOSTEST.docx"
}
else if str[str.count - 3] == "d"
     {
        remoteName = "IOSTEST.doc"
}
else
{
    remoteName = "IOSTEST.pdf"
}

and you will need to add this extension

extension String {

var length: Int {
    return count
}

subscript (i: Int) -> String {
    return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> String {
    return self[min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> String {
    return self[0 ..< max(0, toIndex)]
}

subscript (r: Range<Int>) -> String {
    let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
                                        upper: min(length, max(0, r.upperBound))))
    let start = index(startIndex, offsetBy: range.lowerBound)
    let end = index(start, offsetBy: range.upperBound - range.lowerBound)
    return String(self[start ..< end])
}

}

I don't know why this isn't already in the default.

halfer
  • 19,824
  • 17
  • 99
  • 186