6

I have web link, that is something like:

http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf

It may vary in text or extension. What i want is, get "pdf" string and woule be nice to have name of file, which is in that case - "pdf-test".

How to get those strings from web link? Thanks.

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

3 Answers3

18

You can do it by using NSString with pathExtension for the file extension:

let url: NSString = "http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf" // http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf
let fileExtension = url.pathExtension // pdf
let urlWithoutExtension = url.deletingPathExtension // http://hr-platform.nv5.pw/image/comp_1/pdf-test

As @David Berry suggested use the URL-class:

let url = URL(string: "http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf")
let fileExtension = url?.pathExtension // pdf
let fileName = url?.lastPathComponent // pdf-test.pdf
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
6

Use the URL class:

let url = URL(string: "http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf")
print(url?.pathExtension)
print(url?.deletingPathExtension().lastPathComponent)
David Berry
  • 40,941
  • 12
  • 84
  • 95
3

You can do this:

let urlStr = "http://hr-platform.nv5.pw/image/comp_1/pdf-test.pdf"

var  componentsArr = urlStr.components(separatedBy: "/")
if let fileName = componentsArr.last {
    print(fileName)
}
3stud1ant3
  • 3,586
  • 2
  • 12
  • 15