从 Url 获取图像名称 swift
Get Imagename from Url in swift
我有这个urlhttps://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg
我只需要来自 link In ui Image
的 qLgH80SBqNhMRYbDQeccg 图像名称
您可以使用 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
使用 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)
我有这个urlhttps://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg 我只需要来自 link In ui Image
的 qLgH80SBqNhMRYbDQeccg 图像名称您可以使用 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
使用 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)