get Data from alamofire (responseString) - ios

I am retrieving the data with this code
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers)
.responseString() { response in
switch response.result {
case .success(let data):
let jsonData = JSON(data)
print(jsonData)
case .failure(let error):
print("\(error) - hello world")
}
}
and the result that has sent by the server is
{"result":"Opertion is successfull"}
but i just want the value part "Opertion is successfull"

Use the code from the almofire documentation
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers)
.responseString() { response in
if let jsonData = response.result.value {
print("JSON: \(jsonData)") // serialized json response
}
}

Related

Alamofire Value of type 'Result<Any, AFError>' has no member 'isSuccess' (Swift 5)

I have a simple procedure, which I used in my earlier version (Swift 4). I have now updated to the new version (Swift 5, Alamofire 5.0.0-rc.2), as I am still beginner I got problems with this. Some code parts I could already rewrite.
let headers: HTTPHeaders = [
"SubscriptionKey": SubscriptionKey,
"Host": HostName
]
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
log.error("Error requesting user ID: \(String(describing: response.result.error))")
completion(false, nil)
return
}
guard let json = response.result.value as? [String: Any], let userId = json["userId"] as? String else {
log.error("Malformed result from API call.")
completion(false, nil)
return
}
response.result.isSuccess is not possible. How can I reuse this part?
Error: Value of type 'Result' has no member 'isSuccess'
As a possible solution, I will test the above solution.
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result{
case .success(let value):
//succcess, do anything
case .failure(let error):
log.error("Error requesting user ID: \(String(describing: response.error))")
completion(false, nil)
return
}
Result is containing .success or .failure case.
So you should treat isSuccess like this
switch response.result {
case .success(let value):
//success, do anything
case .failure(let error):
//failure
}

How to post parameters to the server using Alamofire?

I don't know if I am posting the parameters correctly?
func removeCart(rowId: Int, completion: #escaping (Bool)->()) {
let urlString = "\(BaseUrl.Protina.rawValue)/ApiShoppingCart/UpdateCart"
let headers: HTTPHeaders = ["Content-Type": "application/form-data"]
let parameters : [String: Any] = ["removefromcart": rowId]
Alamofire.request(urlString, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let data):
let jsonData = JSON(data)
print(jsonData)
completion(true)
case .failure(let error):
print(error)
}
}
}
when a user tries to remove an item from the cart, the above function gets fired
and after item deleted the rest of the items from cart will return.
Also, I tested it with postman and it was successful.
I found the answer, the problem was in the parameter and encoding.
Changed it to this:
let parameters: [String:Any]= [
"removefromcart": rowId,
"Content-Type" : "application/form-data"
]
And the encoding should be URLEncoding.httpBody

I am trying to get token from post method but I am getting json Response "Get/Method?Not Allowed" I using POST method for this

I am trying to POST email and passowrd and get token in response.
Using same token I have to get Response from server.
Please help me in this case I tried NSURL method and almofire but didnt get proper outhput for the same.
//Check Below code and give me proper output.
func NewsAPI(){
let url = "https://mastleadership.com/api/token-auth"
//Get token logic
let token = ""
let headers = ["Authorization": "token \(token)"]
let params = ["email": "kishor#kishor.com", "password":"abcd"] //This goes in the body of the request
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
if let value = response.result.value {
print(value)
}
}
}
As I understood - you want to post request with params and receive token and again post the same request with the same params? Sorry but there is no logic in that.. But if really thats what you would like to do, than you have to make a request twice, and on response.result you have to save a proper response to your token variable.
Buut.. Anyway If you want to receive token as a response if params (login and password) are correct and than save it, than you could do it like this (Assuming the response from the server is also JSON):
Login request:
func loginRestt(login:String, password:String){
let urlStr = "https://mastleadership.com/api/token-auth"
let params = ["login":login, "password":password]
let headers: HTTPHeaders = ["Content-Type": "application/json"]
Alamofire.request(urlStr, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
print("\(self.TAG), receiving response from login with \(response)")
guard let receivedResponse = try! JSONSerialization.jsonObject(with: response.data!, options: []) as? [String:Any] else {
print("\(self.TAG), Error parsing response from login for json")
return
}
//Here I get token and save it to preferences
if let token:String = receivedResponse["token"] as? String {
print("\(self.TAG), \(token)")
UserDefaults.standard.set(token, forKey: preferencesKeys.loginToken)
} else {
print("\(self.TAG), error receiving token")
return
}
case .failure(let error):
print("\(self.TAG), error receiving response for login with \(error)")
return
}
}
}
And than for any other request that need token just add token in headers like in that example:
let token = UserDefaults.standard.value(forKey: preferencesKeys.loginToken)
let headers: HTTPHeaders = ["Authorization": "token \(token!)"]
RestService.shared.almgr.request(urlStr, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
//response received
case .failure(let error):
//problems
}

swift 3.0: Extra argument in call [duplicate]

I have migrated my project to Swift 3 (and updated Alamofire to latest Swift 3 version with pod 'Alamofire', '~> 4.0' in the Podfile).
I now get an "Extra argument in call" error on every Alamofire.request. Eg:
let patientIdUrl = baseUrl + nextPatientIdUrl
Alamofire.request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding: .JSON)
Can anybody tell me why ?
According to Alamofire documentation for version 4.0.0 URL request with HTTP method would be followings:
Alamofire.request("https://httpbin.org/get") // method defaults to `.get`
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
So your url request will be:
Alamofire.request(patientIdUrl, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
and a sample request will be:
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [AUTH_TOKEN_KEY : AUTH_TOKEN])
.responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
}
Hope this helps!
This one worked for me. No need to remove encoding parameter
Update for Swift 5.x
Alamofire uses the Result type introduced in Swift 5.Also Alamofire.request has been changed to AF.request which will now read their switch response.result value with .success and .failure
AF.request("https://yourServiceURL.com", method: .get, parameters: [:], encoding: URLEncoding.default, headers: ["":""]).responseJSON { (response) in
switch response.result {
case let .success(value):
print(value)
case let .failure(error):
print(error)
}
}
Swift 3.x / 4.x
Alamofire.request("https://yourServiceURL.com", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
and make sure that the parameters are of type
[String:Any]?
In case of Get
Alamofire.request("https://yourGetURL.com", method: .get, parameters: ["":""], encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Even works with
JSONEncoding.default
For Headers
If you are passing headers, make sure their type should be [String:String]
Go through the Parameter Encoding Link
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol
Post method Alamofire 4.0 with Swift 3.0 and xCode 8.0
Alamofire.request(URL, method: .post, parameters: PARAMS)
.responseJSON { closureResponse in
if String(describing: closureResponse.result) == "SUCCESS"
{
// Sucess code
}
else
{
// Failure Code
}
}
My solution is if you are using headers, its type must be [String:String].
This error is up to parameters value. It has to be [String: String]
let url = URL(string: "http://yourURLhere")!
let params: [String: String] = ["name": "oskarko", "email": "youremail#here.com", "sex": "male"]
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<600).responseJSON() { response in
switch response.result {
case .success:
var result = [String:String]()
if let value = response.result.value {
let json = JSON(value)
}
case .failure(let error):
print("RESPONSE ERROR: \(error)")
}
}
I just resolved the same problem as you have. The problem is I have imported Alamofire in the header, so I just remove the Alamofire when call request. Like that:
request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding:
.JSON)
I hope it can help you.
I ran into this same Extra argument 'method' in call error when my URL variable was out of scope.
In your case, please make sure both baseUrl and nextPatientIdUrl are in scope when they are being used Alamofire.request(patientIdUrl,..) method.
Hopefully this resolves your issue. Thanks You!
func API()
{
if Reachability.isConnectedToNetwork()
{
let headers = ["Vauthtoken":"Bearer \(apiToken)"]
print(headers)
// let parameter = ["iLimit":"10","iOffset":"0","iThreadId":"1"]
ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loding...")
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "vehicle/CurrentVehicleLists"), method:.get, parameters:nil, headers: headers).responseJSON { response in
switch response.result {
case .success:
print(response)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
let dictVal = response.result.value
let dictMain:NSDictionary = dictVal as! NSDictionary
let statusCode = dictMain.value(forKey: "status") as! Int
if(statusCode == 200)
{
}
else if statusCode == 401
{
}
else
{
}
case .failure(let error):
print(error)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
}
}
} else
{
ApiUtillity.sharedInstance.dismissSVProgressHUD()
ApiUtillity.sharedInstance.showErrorMessage(Title: "Internet Connection", SubTitle: "Internet connection Faild", ForNavigation: self.navigationController!)
}
}
For me this is working.
For GET Request
Alamofire.request("http://jsonplaceholder.typicode.com/todos/1/get").responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
For POST
let parameters = NSDictionary(object: "nara", forKey: "simha" as NSCopying)
Alamofire.request("http://jsonplaceholder.typicode.com/posts", method: HTTPMethod.post, parameters: parameters as? Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Thanks #Rajan Maheswari.
I fixed this issue with:
Reorder parameters (url then method type).
Change Encoding Enum to be "JSONEncoding.default" for example.
Note that: Alamofire methods signature change in Swift 3
Two things that I found worth noting.
Remove the first url label before its value. Use
Alamofire.request("https://yourServiceURL.com", method: .post,
instead of Alamofire.request(url: "https://yourServiceURL.com",
method: .post,.
Make sure the data type of the parameters is [String:
String]. Declare it explicitly.
I copy this code from Alamofire,create a URLRequest and used Alamofire.request(URLRequest) method, avoid this error
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
I fixed this issue this way:
Just remove extra parameters, just parameters, encoding and headers, if these parameters are nil you can remove then and leave this way,
Alamofire.request(yourURLString, method: .post)
If you have added Alamofire files locally then don't use "Alamofire" before request
let apipath = “your api URL”
request(apipath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch(response.result) {
case .success(_):
do {
let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
return
}
print("Post Response : \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
break
case .failure(_):
print("failure Http: \(String(describing: response.result.error?.localizedDescription))")
break
}
}

How to send request in Alamofire with parameters and headers using POST method in swift

I have a problem with sending a request using Alamofire.
I want to send a POST request with parameters, but I don't know where to put custom header like token.
Here is my code:
let parameters = [
"id": ID,
"recipient_id" : recipientID,
"is_match" : "1"
]
Alamofire.request(.POST, Constants.baseURL + Constants.apiURL + Constants.accept, parameters: parameters, encoding: .JSON)
.validate()
.response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
.responseJSON { response in
switch response.result {
case .Success:
print("Approve Successful")
print("approve \(response)")
case .Failure(let error):
print(error)
}
}
Btw I am using Alamofire 3.4
Alamofire 4.0
let headers = ["Content-Type":"Application/json"]
Alamofire.request(requestString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request \(response.request)")
print("RESPONSE \(response.result.value)")
print("RESPONSE \(response.result)")
print("RESPONSE \(response)")
switch response.result {
case .success:
case .failure(let error):
}
}
in 3.0 u can also add headers like this . In parameters to func

Resources