在swift中从Url获​​取Imagename

时间:2016-07-08 16:15:15

标签: ios swift quickblox

我有这个网址https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg 我只需要来自此链接的qLgH80SBqNhMRYbDQeccg图像名称在ui Image

2 个答案:

答案 0 :(得分:3)

您可以使用NSURL安全地隔离文件名,然后使用子字符串来获取所需的部分。

let s = "https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg"

Swift 2

if let url = NSURL(string: s),
    withoutExt = url.URLByDeletingPathExtension,
    name = withoutExt.lastPathComponent {
    let result = name.substringFromIndex(name.startIndex.advancedBy(5))
    print(result)
}

Swift 3

if let url = URL(string: s),
    withoutExt = try? url.deletingPathExtension(),
    name = withoutExt.lastPathComponent {
    let result = name.substring(from: name.index(name.startIndex, offsetBy: 5))
    print(result)
}

Swift 4

if let url = URL(string: s) {
    let withoutExt = url.deletingPathExtension()
    let name = withoutExt.lastPathComponent
    let result = name.substring(from: name.index(name.startIndex, offsetBy: 5))
    print(result)
}

打印:

  

qLgH80SBqNhMRYbDQeccg

答案 1 :(得分:0)

使用NSURLComponents分解网址的内容如何:

func parseURLForFileName(url:String) ->String?
{
    let components = NSURLComponents(string: url)
    if let path:NSString = components?.path
    {
        let filename = path.lastPathComponent
        if let range = filename.rangeOfString("_-")
        {
            return filename.substringFromIndex(range.endIndex)
        }
    }
    return nil
}

然后你会这样称呼它:

    let name = parseURLForFileName("https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg")
    print(name)