Search code examples
iosswift

How to check url is image or video?


I fetch API response and parse pick url in swift . but i need to check is image url or video url :

If i get image url then show image and if get video url then play video :

 if let url = postMedia?.url{

    //need to check here 
  }

For example

Here is my video url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4
https://clips.vorwaerts-gmbh.de/big_buck_bunny.mov

here is image url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.png
https://clips.vorwaerts-gmbh.de/big_buck_bunny.jpg

note : i know how to show image and play video


Solution

  • You can check image like below

    let url1 : String = "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
            let imageExtensions = ["png", "jpg", "gif"]
            //...
            // Iterate & match the URL objects from your checking results
            let url: URL? = NSURL(fileURLWithPath: url1) as URL
            let pathExtention = url?.pathExtension
                if imageExtensions.contains(pathExtention!)
                {
                    print("Image URL: \(String(describing: url))")
                    // Do something with it
                }else
                {
                   print("Movie URL: \(String(describing: url))")
                }
    

    Same you can check for video