2017-06-21 100 views
1
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/

+0

你爲什麼要指定' 「\(profile_pic_url_hd)」''來代替self.imgURL'直接分配'profile_pic_url_hd'? – rmaddy

+0

'profile_pic_url_hd'是Json類的名稱或任何它叫 –

+0

不,它不是。它是'String'類型的變量。只要做:'self.imgURL = profile_pic_url_hd' – rmaddy

回答

0

您可以使用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

非常感謝! –