1

I am having trouble converting the following curl to a url request in swift.

curl --location --request GET 'https://p52.pocket52.com/apis/v1?p={%22x%22:%22images%22,%22pl%22:{}}'

I Tried the following way, but I got Unexpectedly found nil while unwrapping an Optional value error

var request = URLRequest(url: URL(string: "https://p52.pocket52.com/apis/v1?p={%22x%22:%22images%22,%22pl%22:{}}")!,timeoutInterval: Double.infinity)
    request.httpMethod = "GET"

I tried with the solution present in this link Converting curl to URL request in Swift

but this is a POST curl it doesn't works for GET curl, Since GET request should not contains a body.

Let me define it more clearly, Basically I need to frame the following GET request.

https://p52.xxxx.com/apis/v1?p={"x":"images","pl":""}

We can achieve it by attaching a swift dictionary for a URLComponent part but, hear I am having a nested dictionary that's where I am facing difficulty.

gcharita
  • 7,729
  • 3
  • 20
  • 37
Krishnarjun Banoth
  • 1,410
  • 1
  • 15
  • 30
  • could it be the exclamation mark after the url? – Turo Oct 28 '20 at 10:28
  • @Turo that's the reason why its giving error, but how can we make it to work. One way is we can use guard to avoid the crash, but that is not the final solution, I am getting the response from the server with that curl in post man, and how can we make it in swift? – Krishnarjun Banoth Oct 28 '20 at 10:31
  • did you look at https://stackoverflow.com/questions/24016142/how-do-i-make-an-http-request-in-swift and its answers? – Turo Oct 28 '20 at 10:38
  • Yeah, all of this are how do we make, get and post request in swift, for my case the difficulty exist to make the following url in swift https://p52.pocket52.com/apis/v1?p={"x":"images","pl":{}} – Krishnarjun Banoth Oct 28 '20 at 11:26
  • my last shot: looked at https://stackoverflow.com/questions/27723912/swift-get-request-with-parameters , too? As you see, I'm clueless, too. – Turo Oct 28 '20 at 12:04
  • @Turo, thank you for the help, I tried this too but no luck, the complexity exist to add a nested dictionary params in a url. – Krishnarjun Banoth Oct 29 '20 at 06:33

1 Answers1

3

You can follow this answer like @Turo suggested and build your URL using URLComponents, like so:

var components = URLComponents(string: "https://p52.pocket52.com/apis/v1")
components?.queryItems = [
    URLQueryItem(name: "p", value: #"{"x": "images", "pl" : ""}"#)
]

Then use the url property of URLComponents to compose your URLRequest:

guard let url = components?.url else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
gcharita
  • 7,729
  • 3
  • 20
  • 37