-1

我正在尝试从 documentPicker 获取文件类型。我允许我的用户上传两种 PDF/WORD(doc/docx) 文档类型,知道它是哪一种对我来说至关重要,这样我就可以重命名文件并上传到我的 AWS S3。

任何帮助表示赞赏,我找不到直接从 UIDocumentPickerViewController 获取它的方法。

因此,我试图找到整个 URL 的长度并将长度减去 2/3 以找到第一个字母“d”或“p”,然后我可以相应地设置名称。但是我收到此错误,无法使用类型为“(URL)”的参数列表调用类型为“String”的初始化程序。

 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)
4

2 回答 2

4

最简单的方法是检查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")
}
于 2019-03-06T07:50:25.300 回答
-2

我解决了。我已添加以下有关如何解决此问题的信息:

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"
}

你需要添加这个扩展

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])
}

}

我不知道为什么这不是默认值。

于 2019-03-06T07:47:27.093 回答