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.

6
  • could it be the exclamation mark after the url? Commented Oct 28, 2020 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? Commented Oct 28, 2020 at 10:31
  • did you look at stackoverflow.com/questions/24016142/… and its answers? Commented Oct 28, 2020 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 p52.pocket52.com/apis/v1?p={"x":"images","pl":{}} Commented Oct 28, 2020 at 11:26
  • my last shot: looked at stackoverflow.com/questions/27723912/… , too? As you see, I'm clueless, too. Commented Oct 28, 2020 at 12:04

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.