更改其中包含链接的String

时间:2017-06-21 22:21:30

标签: json swift xcode

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/

1 个答案:

答案 0 :(得分:0)

您可以使用URLComponents,拆分网址路径,然后重建新网址。

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