Learn Courses My Dashboard

Verify if an URL is valid

Hello there, I think that many people will need to know about this sometime soon. For me is the case now.

I am using an API provider to get some data. Well, this API provider does not provide the list with all the STOCKS ( for example stocks, they also have crypto and so on ), they provide, I don’t know why.

Before I access their server, I want to make sure that url exists, or else I will get an app crash.
I found this solution on stack:

func verifyUrl (urlString: String?) -> Bool {
    if let urlString = urlString {
        if let url = NSURL(string: urlString) {
            return UIApplication.shared.canOpenURL(url as URL)
        }
    }
    return false
}


But this will only check if Your APP can open the url, not if it is valid.
You know now my issue, thanks in advance for any help from you. Hope you have a great day!

Instead of trying to validate your URL before you query it, you should be handling failure gracefully. There is no reason why your app should crash if the URL is invalid. Display an error message to the user, show a blank screen with a placeholder message, do something other than crash.

Also you should be using URL(string: “urlHere”)

Not NSURL

let headers = [
“x-rapidapi-key”: Constants.APIkey,
“x-rapidapi-host”: Constants.APIhost
]

    let request = NSMutableURLRequest(url: NSURL(string: "https://alpha-vantage.p.rapidapi.com/query?interval=\(interval)&function=\(function)&symbol=\(symbol)&datatype=json&output_size=\(output_size)")! as URL,
                                            cachePolicy: .useProtocolCachePolicy,
                                        timeoutInterval: 10.0)
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } 

else {

}

The handling method is just if error != nil. I tried with guard, do catch method when I parse the data in my Struct format, but the app still crashes if the url does not exists. If you know a handling method which will prevent crashing, please let me know :slight_smile:

the query parameter represents the symbol of the stock. For instance TSLA exists and I can get the data, but RIOT not, and the app crashes

  1. You should use more recent example code to guide you. You should be using URLRequest instead of NSMutableURLRequest, URL instead of NSURL, etc.
  2. Don’t just check error in your completion handler. There is a reason it gets 3 parameters. You should also be checking response to make sure your request got a valid response back. You probably want to do something like this:
//check for error

//check for valid response
guard let httpResponse = response as? HTTPURLResponse,
    (200...299).contains(httpResponse.statusCode) else {
    //handle an invalid reponse
}

//handle getting valid data