Building The Url
We initialize a URLComponents object and set the scheme host and path attributes with normal string values. The we initialize an array to store the query parameters composed of URLQueryItem objects which we assign to the queryItems attribute and simply append URLQueryItem objects to the array.
import Foundation
var components = URLComponents()
components.scheme = "https"
components.host = "api.flickr.com"
components.path = "/services/rest"
components.queryItems = [URLQueryItem]()
let queryItem1 = URLQueryItem(name: "method", value: "flickr.photos.search")
let queryItem2 = URLQueryItem(name: "api_key", value: "1234")
let queryItem3 = URLQueryItem(name: "text", value: "purple")
components.queryItems!.append(queryItem1)
components.queryItems!.append(queryItem2)
components.queryItems!.append(queryItem3)
print(components.url!)
URLComponentsobjects take care of making sure that our urls are properly escaped and contains safe ASCII characters along with inserting the proper "&", "=", "?" etc.Prints:
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=1234&text=purple