lastPathComponent与deletionLastPathComponent不匹配

时间:2017-08-06 10:39:33

标签: swift firebase firebase-storage

我要求将thumb_添加到网址的文件名

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 deletionLastPathComponent删除图像%2Fjondoe%2Fthumb_-ASDFASDFSDFAS.png,我认为应该有一些更容易/破解的方法来做到这一点,有建议使用云功能 期待收到你们所有人的意见

1 个答案:

答案 0 :(得分:3)

出现此问题的原因是最后两个路径分隔符是转义百分比(%2F),这会混淆deletingLastPathComponent()

我建议在创建用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很快就要去了。