【问题标题】:Change a String that has a link in it更改其中包含链接的字符串
【发布时间】:2017-06-21 22:21:30
【问题描述】:
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/

【问题讨论】:

  • 为什么要将"\(profile_pic_url_hd)"分配给self.imgURL而不是直接分配profile_pic_url_hd
  • profile_pic_url_hd 是 Json 类的名称或其他名称
  • 不,不是。它是String 类型的变量。就这样做:self.imgURL = profile_pic_url_hd
  • 如果我按照你的方式做它就行不通了。它按照我的方式工作!

标签: json swift xcode


【解决方案1】:

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2015-06-23
  • 2013-07-15
  • 2011-10-29
  • 1970-01-01
  • 2022-10-25
  • 2017-06-12
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多