【问题标题】:lastPathComponent doesn't match deletingLastPathComponentlastPathComponent 与删除LastPathComponent 不匹配
【发布时间】:2017-08-06 10:39:32
【问题描述】:

我需要将 thumb_ 添加到 url 的文件名中

let url = "https://firebasestorage.googleapis.com/v0/b/xxx-xx.xxxx.com/o/images%2Fjondoe%2F-ASDFASDFSDFAS.png?alt=media&token=xxxxx" 将其转换为

let url = "https://firebasestorage.googleapis.com/v0/b/xxx-xx.xxxx.com/o/images%2Fjondoe%2Fthumb_-ASDFASDFSDFAS.png?alt=media&token=xxxxx"

我得到了这个工作使用

let webURL  = NSURL(string: url)

var pathArray : [String] = webURL!.pathComponents!

let thumbFile =  pathArray[pathArray.count - 3] + "/" + pathArray[pathArray.count - 2]+"/thumb_\(webURL!.lastPathComponent!)"
print( webURL!.deletingLastPathComponent)
let thumbURL = webURL!.deletingLastPathComponent?.appendingPathComponent(thumbFile)

print(thumbURL!)

我看到的是 lastPathComponent 只给出了文件名 vs deleteLastPathComponent 删除 images%2Fjondoe%2Fthumb_-ASDFASDFSDFAS.png ,我认为应该有一些更简单的 /breakproof 方法来做到这一点,有使用云功能的建议 等期待您的来信

【问题讨论】:

    标签: swift firebase firebase-storage


    【解决方案1】:

    出现问题是因为最后两个路径分隔符被百分比转义(%2F)这混淆了deletingLastPathComponent()

    我建议在创建 URL 之前调用removingPercentEncoding 以将%2F 替换为/

    let urlString = "https://firebasestorage.googleapis.com/v0/b/xxx-xx.xxxx.com/o/images%2Fjondoe%2F-ASDFASDFSDFAS.png?alt=media&token=xxxxx"
    let clearedURLString = urlString.removingPercentEncoding!
    let url = URL(string: clearedURLString)!
    let thumbLastPathComponent = "thumb_" + url.lastPathComponent
    let newURL = url.deletingLastPathComponent().appendingPathComponent(thumbLastPathComponent)
    
    print(newURL)
    

    通常最好的解决方案是使用URLComponents。但转义的正斜杠百分比 (%2F) 未被识别为有效的路径分隔符。

    代码是 Swift 3,强烈建议更新,Swift 4 迫在眉睫。

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2014-09-19
      • 2018-01-01
      相关资源
      最近更新 更多