Pak Ho Cheung
Pak Ho Cheung

Reputation: 1416

URL nil after upgrade to swift 3.0

URL is nil after covert to swift 3.0

my swift2 code (This code works prefect)

let correctedAddress:String! = firstResult.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.symbolCharacterSet())
let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in

my swift 3 code after convert

print(firstResult)
let correctedAddress:String! = firstResult.addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
print(correctedAddress)
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)")
print(url)
let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in

print

San Francisco, California, United States    
%53%61%6E%20%46%72%61%6E%63%69%73%63%6F%2C%20%43%61%6C%69%66%6F%72%6E%69%61%2C%20%55%6E%69%74%65%64%20%53%74%61%74%65%73
nil

Tried to look at the question in here. Convert String to NSURL is return nil in swift

var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" 
var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 
var searchURL : NSURL = NSURL(string: urlStr)! 
println(searchURL)

But, I still could figure out the NSUTF8StringEncoding since it occurs an error

Upvotes: 1

Views: 1803

Answers (2)

ronak patel
ronak patel

Reputation: 400

try this

if let address = firstResult.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
        let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(address)") {
        print(url)
    }

Upvotes: 0

serg_zhd
serg_zhd

Reputation: 1043

Try this:

let firstResult = "San Francisco, California, United States"
print(firstResult)
if let correctedAddress = firstResult.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)") {
    print(url)
}

Upvotes: 1

Related Questions