Home > AI > IOS > Foundation >

URLComponents

Example 1: Basic usage

var components = URLComponents()
components.scheme = "https"
components.host = "postman-echo.com"
components.path = "/time/valid"
components.queryItems = [
    URLQueryItem(name: "timestamp", value: "2016-10-10"),
]

let url = components.url
print(url!)

//https://postman-echo.com/time/valid?timestamp=2016-10-10

Example 2: private extension to add API key. In the extension of URLComponents, it return a copy of original URLComponets, you can check this in the ContentView

private extension URLComponents {
    func addingApiKey(_ apiKey: String) -> URLComponents {
        var copy = self
        copy.queryItems = [URLQueryItem(name: "api_key", value: apiKey)]
        return copy
    }
    
    var request: URLRequest? {
        url.map { URLRequest.init(url: $0) }
    }
}




struct ContentView: View {
    
    init() {
        let a = URLComponents(string:"https://postman-echo.com/time/valid")
        let b = a?.addingApiKey("Good")
        print(b?.url!)
    }
    
    var body: some View {
        Text("good")
    }
}

Example 3: This extension would modify the original URLComponents directly.

private extension URLComponents {
    mutating func addingApiKey(_ apiKey: String)  {
        self.queryItems = [URLQueryItem(name: "api_key", value: apiKey)]
    }
    
    var request: URLRequest? {
        url.map { URLRequest.init(url: $0) }
    }
}


struct ContentView: View {
    
    init() {
        var a = URLComponents(string: "https://good.com")
        a?.addingApiKey("Good")
        print(a?.url!)
    }
    
    
    var body: some View {
        Text("good")
    }
}

Leave a Reply