I have a Swift 4 project that I'm trying to learn a few new things and incorporate them at them same time, however I am stuck on something I just can't seem to work out.
import Foundation
protocol Endpoint {
var baseUrl: String {get}
var path: String {get}
var queryItems: [URLQueryItem] {get}
}
extension Endpoint {
var urlComponent: URLComponents{
var component = URLComponents(string: baseUrl)
component?.path = path
component?.queryItems = queryItems
return component!
}
var request: URLRequest{
return URLRequest(url: urlComponent.url!)
}
}
enum StoryEndpoint: Endpoint{
case storiesList(type: String)
var baseUrl: String{
return "https://www.XXXXXXXXXXX.com/greeley"
}
var path: String{
switch self {
case .storiesList(let type):
return "/api/items"
}
}
var queryItems: [URLQueryItem]{
return []
}
}
Underneath enum StoryEndpoint, you can see I've set baseUrl, path, and queryItems, but if I run the project, it returns a custom error label defined in another file.
However, if I change:
var baseUrl: String{
return "https://www.XXXXXXXXXXX.com/greeley"
}
To this (basically merging the baseUrl and path):
var baseUrl: String{
return "https://www.XXXXXXXXXXX.com/greeley/api/items"
}
It returns the decoded items in my console correctly.
Have I set up something incorrectly with the urlComponent?
When you instantiate a URLComponents like this:
var component = URLComponents(string: baseUrl)
It creates something like this:
[URLComponents]
scheme: "https"
host: "www.XXXXXXXXXXX.com"
path: "/greeley"
queryItems: nil
...
You see what happens if you execute component?.path = path after it.
[URLComponents]
scheme: "https"
host: "www.XXXXXXXXXXX.com"
path: "/api/items"
queryItems: nil
...
This may not be what you want.
You may need to write something like this:
component?.path += path
(If you think considering "/" is sort of annoying, you may need to find other way around.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With