How to make an HTTP GET Request with Parameters. SwiftyJSON Swift - swift

Below mentioned snippet is working just fine. It queries JSON data. I just want to know how can I pass parameters with this.
let filePath = NSURL(string: "http://localhost:2403/postedjob")
let jsonData = NSData(contentsOfURL:filePath!)
let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)
I want to pass this parameters:
let params = ["$limit": 2, "$sort": ["id":"+1"]] as Dictionary<String, AnyObject>

Alamofire may be a good option for you to pass the parameters.
https://github.com/Alamofire/Alamofire

For a GET request pass parameters in the query string (the part after the "?" mark).
For a POST request parameters can be sent in the body in a number of ways. Raw data, form data and JSON among other methods.
Of course the server has to match the method used.

Related

Swfit URLRequest POST How to make a request with duplicated parameter keys

I'm currently working on a project which uses Inoreader APIs, and there is one required post request with duplicated parameter keys.
https://www.inoreader.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&i=12345678&i=12345679
As you can see duplicated i parameters. I've tried below to set httpBody of URLRequest, failed silently.
var parameters = [String: Any]()
parameters["i"] = idArray
parameters["a"] = "user/-/state/com.google/read"
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = jsonData
// I omitted other codes for simplicity
Then I've tried to chain every element of idArray with "&i=", assigned it to parameters["i"], also failed silently.
// chainedID was something like 123&i=456&i=789, to make it looks like as url example given by documentation
parameters["i"] = chainedID
How can I do that? This API is working perfectly with one item, but I can't get it work on multiple items. It claims will work with multiple items.
Based on the example that you posted and the ones that the documentation mentions, although the request is POST can accept parameters in the URL's query.
So, the solution would be to compose your request using URLComponents:
var components = URLComponents(string: "https://www.inoreader.com/reader/api/0/edit-tag")
var queryItems = [
URLQueryItem(name: "a", value: "user/-/state/com.google/read")
]
idArray.forEach {
queryItems.append(URLQueryItem(name: "i", value: $0))
}
components?.queryItems = queryItems
guard let url = components?.url else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
and not use JSON parameters in the request's body.

How to parse URL # fragments with query items in Swift

Query parameters sometimes get passed as URL fragments instead of query parameters - e.g. during OAuth flows to provide client-only access to parameters.
What's the simplest way to parse a URL like:
https://example.com/auth-callback#access_token=mytoken&expires_in=36000&scope=zap+profile
into key values for:
access_token, expires_in, scope
Simply pass the fragment property as a query string to a new URLComponent and read the parsed query objects:
let url = URL(string: "https://example.com/auth-callback#access_token=mytoken&expires_in=36000&scope=zap+profile")
var components = URLComponents()
components.query = url.fragment
for item in components.queryItems! {
print("\(item.name): \(item.value)")
}

whitespace in url - alamofire

I'm trying to post a http request using alamofire. my request is as follows:
let url = "\(myBaseURL)/{name:adriana lima}"
Alamofire.request(url.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!, method: .post)
I tried some encoding types such as :
urlFragmentAllowed , whitespaces
but they're not working.
I know if i use parameters, whitespace would be handled but in this case, i have to pass parameters inside of url. but it results error. how can i post this and how should i encode it ?
You need to encode the URL before passing it to alamofire method. using addingPercentEncoding.
let urlString = "\(myBaseURL)/{name:adriana lima}"
guard let encodedURL = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
//Invalid URL
return
}

Passing array in parameter with Alamofire (.GET)

I am using Alamofire 3.0
The following is my code
var ignoreIDs = [Int]()
self.ignoreIDs.append(2)
let parameters = ["ignore_ids": self.ignoreIDs]
Alamofire.request(.GET, AppDelegate.kbaseUrl + "surveys/me", parameters: parameters, encoding: .JSON)
.responseJSON {
response in
}
However, the result of print(response.result) just shows FAILURE.
Is there any way to get more information? Also, is this the correct way to pass an array as parameters?
P/S: Yes server side is indeed expecting an array.
To print out additional information about the result, you should use debugPrint(response.result).
var ignoreIDs = [Int]()
self.ignoreIDs.append(2)
let parameters = ["ignore_ids": self.ignoreIDs]
Alamofire.request(.GET, AppDelegate.kbaseUrl + "surveys/me", parameters: parameters, encoding: .JSON)
.responseJSON { response in
debugPrint(response)
debugPrint(response.result)
}
Both of these are overridden to provide more detail about the actual response.
sorry apparently it's my own fault. My method is a GET, so as Johnny mentioned I'm parsing in a form that the server wasn't expecting.
The answer for me should be append the parameters as a query string and to my base url.

Send a [[String:AnyObject]] using SwiftyJSON

I am requesting to an API using SwiftyJSON. I want to pass a value to a key which is in [[String: AnyObject]]:
var params = [String: AnyObject]()
parameters["paymentOptions"] = [["billingId": 1]]
So, directly passing it like this and making a request gave no response. So, I tried it like this:
var params = [String: AnyObject]()
parameters["paymentOptions"] = "\([["billingId": 1]])"
This gives an error from the API. I think I am doing something wrong here. How should I be sending the array?
This is how I make a request.
request(.POST, pathUrl, parameters: params)