Json 更改包含链接的字符串

Json 更改包含链接的字符串,json,swift,xcode,Json,Swift,Xcode,self.imgURL是一个链接,也是一个字符串。例如,链接是: let profile_pic_url_hd = user["profile_pic_url_hd"] as! String self.imgURL = "\(profile_pic_url_hd)" 是否有人知道如何将此链接更改为: https://scontent-frx5-1.cdninstagram.com/t51.2885-19/s320x320/19121160_1328742810566926_6482637033

self.imgURL
是一个链接,也是一个字符串。例如,链接是:

let profile_pic_url_hd = user["profile_pic_url_hd"] as! String
self.imgURL = "\(profile_pic_url_hd)"
是否有人知道如何将此链接更改为:

https://scontent-frx5-1.cdninstagram.com/t51.2885-19/s320x320/19121160_1328742810566926_6482637033138290688_a.jpg

换句话说,在没有
/s320x320/
的情况下,您可以使用
URLComponents
,拆分URL路径,并重建新的URL

https://scontent-frx5-1.cdninstagram.com/t51.2885-19/19121160_1328742810566926_6482637033138290688_a.jpg
输出:

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

您可以使用
URLComponents
,拆分URL路径,然后重新生成新的URL

https://scontent-frx5-1.cdninstagram.com/t51.2885-19/19121160_1328742810566926_6482637033138290688_a.jpg
输出:

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

为什么要将
“\(profile\u picu url\u hd)
分配给
self.imgURL
,而不是直接分配
profile\u picu url\u hd
呢?
profile\u picu url\u hd
是Json类的名称或其他名称,不是。它是一个
String
类型的变量。只需这样做:
self.imgURL=profile\u pic\u url\u hd
如果我按你的方式做,它不会起作用。。这是我的方式!为什么要将
“\(profile\u picu url\u hd)
分配给
self.imgURL
,而不是直接分配
profile\u picu url\u hd
呢?
profile\u picu url\u hd
是Json类的名称或其他名称,不是。它是一个
String
类型的变量。只需这样做:
self.imgURL=profile\u pic\u url\u hd
如果我按你的方式做,它不会起作用。。这是我的方式!非常感谢你!非常感谢你!