Convert String to NSURL is return nil in swift

前端 未结 6 553
你的背包
你的背包 2020-12-01 09:15

I am trying to convert a String to NSURL and my code for that is Below:

var url = \"https://maps.googleapis.com/maps/api/distancema         


        
6条回答
  •  时光说笑
    2020-12-01 09:49

    SWIFT 3.0

    A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"

    guard let url = NSURL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                else
                {
                    print("Couldn't parse myURL = \(urlPath)")
                    return
                }
    

    The variable called "urlPath" in my above example would be the url string you have already declared somewhere else in your code.

    I came across this answer because randomly I was getting the nil error with XCode breaking at the point my string was made into a NSURL. No logic as to why it was random even when I printed the url's they would look fine. As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.

    tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url.

提交回复
热议问题