all.
I study iOS and alamofire.
I tried to connect Login API url. It is correctly operating.
this is code.
var rTest = Alamofire.request(self.authLoginUrl, method: .post)
.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)")
}
}
}
and i want to post id and password
let params = ["Username": "ryulstory", "Password": "1234!"]
var rTest = Alamofire.request(self.authLoginUrl, method: .post, Parameters: params)
.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)")
}
}
}
there are error :Extra argument 'method' in call.
the error doesn't show if i don't put params.
what is problem? could you help me?
best regards.
Assuming your backend receives and returns JSON, this should work
let params: Parameters = [
"Username": "ryulstory",
"Password": "1234!"
]
//if server accepts and returns JSON
Alamofire.request(self.authLoginUrl, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate().validate(contentType: ["application/json"])
.responseJSON() { response in
switch response.result {
case .success:
print("Success")
case .failure(let error):
print("Failure")
}
}
.response { response in
log.debug("Request: \(String(describing: response.request))")
log.debug("Response: \(String(describing: response.response))")
log.debug("Error: \(String(describing: response.error))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
log.debug("Data: \(utf8Text)")
}
}
Related
I been trying to post parameters contain Arabic characters using almofire .
When i send latin chars everything well done .
But when i send Arabic characters it appears like this '?? ???? ?? ?'
How i can solve this problem please help me .
My code :
var myUrls:String = "https//:wwww.mywebsite.com"
let parameters: Parameters = [
"user_id": "\(is_loged)",
"title": "\(title)",
"msg": "\(msg)",
"appKey": "\(staticsClass.AppKey)"
]
Alamofire.request(myUrls, method: .post, parameters: parameters ).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
let toast = Toast(text: NSLocalizedString("sent_successfully", comment: ""))
toast.show()
}
}
you need to set Content-Type header to request:
var myUrls = URLRequest(url: URL(string: "https//:wwww.mywebsite.com")!)
myUrls("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
Alamofire.request(myUrls, method: .post, parameters: parameters ).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
let toast = Toast(text: NSLocalizedString("sent_successfully", comment: ""))
toast.show()
}
}
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
}
I am making a request to a local server that returns the following JSON:
{"session_key":"somecodexyz1234"}
The following code is is used to attempt to print the session_key value. But this is always evaluated tonil`.
Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Response code: \(String(describing: response.response?.statusCode))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}}
if response.data != nil {
let json = JSON(data: response.data!)
// changes
if let arr : NSArray = json as? NSArray
{
let sk = arr.value(forKey: "session_key") as? String
if sk != nil {print(sk)}
}
}
The following is output (the print(sk) is not executed as it is nil):
Request: Optional(http://127.0.0.1:5000/code)
Response: Optional(<NSHTTPURLResponse: 0x60800023f260> { URL: http://127.0.0.1:5000/code } { status code: 200, headers {
"Content-Length" = 40;
"Content-Type" = "application/json";
Date = "Sat, 23 Sep 2017 06:02:25 GMT";
Server = "Werkzeug/0.12.2 Python/3.4.3";
} })
Response code: Optional(200)
Data: "{\"session_key\":\"somecodexyz1234\"}"
Use below code to get response from almofire in json. In Your code, your are directly checking response.data instead of first check response.result as below.
Alamofire.request(requestURL, method:.post, parameters: param as? Parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON(completionHandler: { (response) in
switch response.result
{
case .success(let responseJSON):
// If request success then you will get response in json here
if responseJSON is String{
print("Reponse is string")
}
else if responseJSON is NSDictionary{
print("Reponse is Dictionary")
}
else if responseJSON is NSArray{
print("Reponse is Array")
}
else{
print("Any object")
return
}
print("Response : \((dicResponse)")
break
case .failure(let error):
// If request is failure then got error here.
break
}
})
You are using SwiftyJSON so why you again convert let arr : NSArray = json as? NSArray like this. You can simply do like this.
Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Response code: \(String(describing: response.response?.statusCode))")
if response.result.isSuccess, let result = response.result.value {
let json = JSON(result)
// Here is your session key
let sk = json["session_key"].stringValue
} else {
//Failure
}
})
Hello i am using Alamofire but i am getting "Invalid JSON." in the response and i have used following code-
parametersV = ["username":amrit21#yopmail.com, "password":123456]
let headers = ["Content-Type": "application/json", "x-csrf-token":""]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, headers: 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 Solved it
let parametersV = ["username":"amrit21#yopmail.com", "password":"123456"]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, encoding: .JSON)
.responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
It was a problem was encoding you were not encoding your JSON request. use encoding: .JSON
Some times when in response there is not proper JSON then piece of code .responseJSON { response in throws exception and we can't see what type of response has been received. in such case we can print it to console before converting to .responseJSON { response in
Below is full example
public func deleteImage(_ photoId: Int) {
let requestURL = URL(string: APPURL.BASE_API_URL + "postApi/deletePostPhoto")!
let paramDict: [String: String] = ["photoId": String(photoId), "accessKey": APP_DELEGATE.loggedInUser.accessKey, "language":APP_DELEGATE.language.lowercased()]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in paramDict {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
},
usingThreshold:UInt64.init(),
to: requestURL ,
method:.post,
headers:nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
// this is point where we can get actual response recieved from server, it may have some html , xml or anything
upload.responseData(completionHandler: { response in
print(response)
let responseData = String(data: response.data!, encoding: String.Encoding.utf8)
print("responseData=",responseData ?? "none")
})
// if there is proper JSON recieved it will be executed otherwise it will fall in failure
upload.responseJSON { response in
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
print("response JSON: ",swiftyJsonVar)
}
else {
let error = response.error
print(error?.localizedDescription ?? "")
}
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
})
}
In the java app we get response from the REST as String by using de below code.
String response = performPostCall(wmeAPI.vote("" + rowItem.getPoll_id()), has);
In swift I am making post call with Alamofire
I made post call
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseString
{ response in switch response.result {
case .Success(let JSON):
print("Success \(JSON)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
How can I get the response string from this post call.
You need to use response JSON
So, Change responseString to responseJSON
For Example :
Alamofire.request(.GET, "YOUR_URL").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
}
}
For POST call :
Alamofire.request(.POST, "YOUR_URL", parameters: nil, encoding: ParameterEncoding.JSON, headers: nil).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
print(resJson)
}
if responseObject.result.isFailure {
let error : NSError = responseObject.result.error!
print(error)
}
}
if you check Alamofire Doc., there is already define the things that how to get response String and how to get response JSON
Response JSON handler
Alamofire.request(.GET, "https://httpbin.org/get")
.responseJSON { response in
debugPrint(response)
}
Response String handler
Alamofire.request(.GET, "https://httpbin.org/get")
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
Chained Response Handlers
Alamofire.request(.GET, "https://httpbin.org/get")
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
Refer Alamofire Usage