Search code examples
swift3nsurl

NSURL returning nil with Swift 3.0


While running this code with Swift 2.3, it was fine. When I started to update my code for Swift 3, the problem started. My NSURL returns zero when I use the below code:

{

var searchResults: [String]!

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let correctedAddress = self.searchResults[indexPath.row].addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)        
let urlpath:NSString! = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)" as NSString!
let url = NSURL.init(string: urlpath as String)

}

 }           

I am very new to iOS programming, so my question may be very basic. I have Googled a lot but could not find an answer.


Solution

  • In Swift there is lot of changes in the syntax, You can make your URL like this:-

    let correctedAddress = "Delhi " //You can replace your address here
    let urlpath = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let url = URL(string: urlpath!)
    print(url!)
    

    Result:- https://maps.googleapis.com/maps/api/geocode/json?address=Delhi%20