快速从 Url 获取 Imagename
Posted
技术标签:
【中文标题】快速从 Url 获取 Imagename【英文标题】:Get Imagename from Url in swift 【发布时间】:2016-07-08 16:15:14 【问题描述】:我有这个网址https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg 我只需要来自此链接的 qLgH80SBqNhMRYbDQeccg 图像名称 In ui Image
【问题讨论】:
【参考方案1】:您可以使用 NSURL 安全地隔离文件名,然后使用子字符串来获取您想要的部分。
let s = "https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg"
斯威夫特 2
if let url = NSURL(string: s),
withoutExt = url.URLByDeletingPathExtension,
name = withoutExt.lastPathComponent
let result = name.substringFromIndex(name.startIndex.advancedBy(5))
print(result)
斯威夫特 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)
斯威夫特 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
【讨论】:
【参考方案2】:使用NSURLComponents
分解 URL 的东西怎么样:
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)
【讨论】:
以上是关于快速从 Url 获取 Imagename的主要内容,如果未能解决你的问题,请参考以下文章