I'm trying to get an image from url like this:
var string = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI¢er=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="
let url = NSURL(string: string.stringByRemovingPercentEncoding!)
if let data = NSData(contentsOfURL: url){
let image = UIImage(data: data)
}
but it returns nil the url
. It seems like the url doesn't exists but it is, if you go to the url you will see an image.
So what is the problem with the cast? or how can I get this image.
The problem is the vertical bars (|
) in the query part of your URL. They should be escaped as %7C
.
Here's how I would construct the URL which auto-escape the query part:
var components = NSURLComponents(string: "https://maps.googleapis.com/maps/api/staticmap")!
components.query = "key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI¢er=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="
if let url = components.url {
// ...
}
If you are using Swift 3, NSURLComponents
is renamed to URLComponents