So I am trying to POST to my API on my iPhone app. When I POST I want to be able to return a struct that has data. How would I do that? So far I have
Alamofire.request(.POST, "API_URL", parameters)
Is there some way to store what the API gives back?
Try using this
Alamofire.request(.POST, "API_URL, parameters).responseJSON{ request, response, result in
print(result.value)
}
If you want to use the resulting JSON in an easy manner - I would suggest using SWIFTY JSON
Yes you can.If you are using the latest version of Alamofire.
Simply try this(If the returning data is in JSON)
let url1 = "http://yoururl.com"
let head = [ "Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json;charset=UTF-8"] // Adding headers
let p = ["Email":"anything","Password": "123"] // Adding parameters if any
Alamofire.request(.POST,url1, parameters: p, encoding : .JSON, headers : head)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
}
Related
I want to add the JSON object in GET request with URL. Please refer below URL.
https://testdata.com/xyz/&form={"id":"12", "data": "3"}
I am getting nil while converting String to URL
let serviceUrl = URL(string: url)
Thanks in advance.
I was already tried below solution but unfortunately no luck.
JSONSerialization.data
converting to string with utf8
removed whitespaces if any
addingPercentEncoding with URL host allowed
It's not recommended, to send a request body with GET request. GET request means to fetch all the resources/content that this URL has to offer. If they are parsing the GET body on server side, it's against the semantics. But if you really need to do it. Use Almofire. Here's a Sample Code.
let parameters : [String : Any] = [
"id":"12",
"data":"3"
]
func getContent(parameters: [String: Any]) {
Alamofire.request("http://18.218.235.193:3000/user/securedtoken", method:
.get, parameters: parameters, encoding: JSONEncoding.default)
.responseObject {(response:
DataResponse<YOUR RESPONSE MODEL HERE>) in
let response = response.result.value
//Do Something (Success)
}
}
I recommend you to use Alamofire library. You can do what you want using following code snippet
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["form": ["id": 12, "data": 3]])
.response { request, response, data, error in
print(request)
print(response)
print(error)
}
I am new to iOS and want to call an API for login. I am using Alamofire for HTTP request. I am getting a response from the server but I guess it is saving response in cache. So if I call api with different data is printing same response again. And one more question is I want to save session for later api call. How can I save session data and use it in header for later api call?
This is my Login API Call
let params = ["identity": txtId.text!, "pass": txtPassword.text!]
AF.request(LOGIN_URL, method: .post, parameters: params as Parameters).responseJSON { response in
print("response = \(response.result.value)")
}
One easy way to remove caches is to call this code before your network call:
URLCache.shared.removeAllCachedResponses()
Or you can also remove caches for a single request:
let urlRequest = URLRequest(url: URL(string: "https://...")!)
URLCache.shared.removeCachedResponse(for: urlRequest)
Then, make your network call:
let params = ["identity": txtId.text!, "pass": txtPassword.text!]
AF.request(LOGIN_URL, method: .post, parameters: params as Parameters).responseJSON { response in
print("response = \(response.result.value)")
}
I'm trying to do a query request in Alamofire, this needs to be correct fetch request link (It is working when try in browser).However, query part comes on the last part of request in Alamofire. It needs to come just after Ctemp. How can I change the order?
https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp?q={"value": "50.50"}&apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI
Swift Code;
let parameters: Parameters = ["q" : ["value" : "50.50"],
"apiKey": "2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI"]
Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp", method: .get, parameters: parameters,encoding: URLEncoding.default, headers: nil).responseData{ response in
print(response.request)
print(response.response)
print(response.result)
}
response.request which is incorrect and fetches all the datas and don't do query;
Optional(https://api.mlab.com/api/1/databases/mysignal/collections/Ctemp?apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI&q%5Bvalue%5D=50.50)
I don't think the parameters in Alamofire are going to treat the nested dictionary properly. It is url encoding those parameters in the url you show as the output. I would suggest changing:
let parameters: Parameters = ["q" : ["value" : "50.50"],"apiKey": "2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI"]
To:
let parameters: Parameters = ["q" : "{\"value\" : \"50.50\"}", "apiKey": "2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI"]
I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";
One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.
I am trying to make a JSON Request with Alamofire but the response is in Greek and Swift returns:
Response
{
id = 4;
name = "\U0395\U03bb\U03b1\U03b9\U03cc\U03bb\U03b1\U03b4\U03bf"
url = "http://www.gaiaskarpos.com/app/images/categories/olive.png";
}
The problem is at name field.
//Swift Alamofire Request
Alamofire.request(.GET, "http://gaiaskarpos.com/applegetCategores.php",
encoding:.JSON).validate().responseJSON{(response)->
Void in print("Response Json : \(response.result.value)")
I had a same issue in Arabic/Persian chars and It's my solution:
json variable :
{
message = "\U062f\U0633\U062a\U06af\U0627\U0647 \U0645\U0639\U062a\U0628\U0631 \U0646\U06cc\U0633\U062a";
status = 0;
}
So I casted json to [String: AnyObject] :
var test = json as? [String : AnyObject]
print(test)
It's fixed. You should give it a try.
Why is your encoding .JSON? You send .GET-request and you don't need to specify the type of encoding in your request.
Alamofire documentation say:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So use it. Links -> http://cocoadocs.org/docsets/Alamofire/1.1.3/ and https://github.com/Alamofire/Alamofire
You must specify the type of encoding when you pass parameters in the body of your request. It is for .POST and .PUT requests.
Try to print 'name' to Debug area. Maybe you'll get name in normal encoding... Xcode has the disadvantage: it shows not-UTF8 data in response like '\U0395\U03bb ... ... ... \U03b1\U03b9\' when there is some level of nested data in response.
Try to use NSUTF8StringEncoding with alamofire response
encoding: NSUTF8StringEncoding
Try to serialize the JSON with below code this might help you
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]