更改包含链接的字符串
问题描述:
let profile_pic_url_hd = user["profile_pic_url_hd"] as! String
self.imgURL = "\(profile_pic_url_hd)"
self.imgURL
是一个链接,它是一个字符串。该链接,例如:更改包含链接的字符串
https://scontent-frx5-1.cdninstagram.com/t51.2885-19/s320x320/19121160_1328742810566926_6482637033138290688_a.jpg
有谁知道如何此链接更改为:
https://scontent-frx5-1.cdninstagram.com/t51.2885-19/19121160_1328742810566926_6482637033138290688_a.jpg
换句话说,没有/s320x320/
。
答
您可以使用URLComponents
,分割URL的路径,并重建一个新的URL。
let urlstr = "https://scontent-frx5-1.cdninstagram.com/t51.2885-19/s320x320/19121160_1328742810566926_6482637033138290688_a.jpg"
if var comps = URLComponents(string: urlstr) {
var path = comps.path
var pathComps = path.components(separatedBy: "/")
pathComps.remove(at: 2) // this removes the s320x320
path = pathComps.joined(separator: "/")
comps.path = path
if let newStr = comps.string {
print(newStr)
}
}
输出:
https://scontent-frx5-1.cdninstagram.com/t51.2885-19/19121160_1328742810566926_6482637033138290688_a.jpg
+0
非常感谢! –
你为什么要指定' “\(profile_pic_url_hd)”''来代替self.imgURL'直接分配'profile_pic_url_hd'? – rmaddy
'profile_pic_url_hd'是Json类的名称或任何它叫 –
不,它不是。它是'String'类型的变量。只要做:'self.imgURL = profile_pic_url_hd' – rmaddy