dedicatedCoder dedicatedCoder - 11 months ago 130
iOS Question

Get Imagename from Url in swift

I have this url https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg
I need only qLgH80SBqNhMRYbDQeccg image name from this link In ui Image

Answer Source

You can use NSURL to safely isolate the filename then use substring to get the part you want.

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)
}

Prints:

qLgH80SBqNhMRYbDQeccg

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download