I'm using NSURLComponents
to generate a URL for an API call in Swift:
func generateSearchByLocaleURL(lat: Int, lon: Int) -> String {
var components = NSURLComponents()
let bbox = generateBboxValue(lat, lon)
components.scheme = "https"
components.host = "api.flickr.com"
components.path = "/services/rest/"
components.queryItems = [
NSURLQueryItem(name: "method", value: "flickr.photos.search"),
NSURLQueryItem(name: "api_key", value: "KEY_VALUE"),
NSURLQueryItem(name: "bbox", value: bbox),
NSURLQueryItem(name: "extras", value: "url_m"),
NSURLQueryItem(name: "format", value: "json"),
NSURLQueryItem(name: "nojsoncallback", value: "1")
]
let url = components.string
return url!
}
I have a helper method to determine the string to use in one of the NSURLQueryItem
objects based on the input from two textFields on screen called generateBboxValue()
:
func generateBboxValue(lat: Int, lon: Int) -> String {
let lat1 = lat - 1
let lat2 = lat + 1
let lon1 = lon - 1
let lon2 = lon + 1
let bbox = "\(lat1)&2C"+"\(lat2)%2C"+"\(lon1)%2C"+"\(lon2)"
return bbox
}
generateSearchByLocaleURL(20, 25)
As you can see there is a comma ( , ) in the string, and I need that to be generated to %2C when it's input to the NSURLComponents
. However when I print the returning string from NSURLComponents.string
I get:
"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=KEY_VALUE&bbox=19%262C21%252C24%252C26&extras=url_m&format=json&nojsoncallback=1"
Which if you'll notice in the 'bbox' key/value portion is returning:
bbox=19%262C21%252C24%252C26
How do I return just %2C in this scenario?? This is preventing me from successfully making any API calls and I'm banging my head against the wall.
Just do let bbox = "\(lat1),\(lat2),\(lon1),\(lon2)"
, so then when it gets turned into a URL, the comma converts to %2C. I removed the +
because you don't need it at all, you can just string them together in one string.