Persian Characters in URL (with Alamofire) - swift

i have variables and i want put them in url to post
some variables can be persian or english characters
everything is well when characters are english
but when i use persian characters alamofire respond invalid url
the code is .
let headers : Dictionary = [
"Content-Type":"application/json"
];
let request = Product_Rename() .
request.newName = string .
request.productId = UInt(_Data[deletIndex].ProductId!)
Alamofire.request("http://example.com/api/product/rename?productId=\(_Data[deletIndex].ProductId!)&newName=\(string)&AUTHID=\(authID!)",
method: .put,
headers: headers)
.validate(statusCode: 200..<300)
.responseString(completionHandler: {response in
})
.responseJSON(completionHandler: {response in
switch response.result{
case .success:
if let data = response.data, let utf8Text = String(data:data,encoding:.utf8){
let x = Product_Rename_Response(json:utf8Text)
if x.success == true {
self._Data[self.deletIndex].Name = string
self._ProductTable.reloadData()
}else{
self.dismiss(animated: true, completion: nil)
}
}
case .failure(let error):
print(error)
break
}
})

You have to escape the special characters from the URL.
request.productId = UInt(_Data[deletIndex].ProductId!)
let url = "http://example.com/api/product/rename?productId=\(_Data[deletIndex].ProductId!)&newName=\(string)&AUTHID=\(authID!)"
if let encodedUrl = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) {
Alamofire.request(encodedUrl,
method: .put,
headers: headers)
.validate(statusCode: 200..<300)
.responseString(completionHandler: {response in
})
// use the data
}
The method addingPercentEncoding(withAllowedCharacters:) will encode the characters into percent encoding (e.g. https://example.com/foo.php?text=bar%20baz, where %20 represents a space).

Related

Alamofire get method with parameters in the url with header swift

I have a get method with 3 parameters on the base url itself.I have tried the following code, but it is going to failure condition saying either not a valid url or not a valid JSON.
What is the correct way to approach this?
The code i have used is as below:
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification?" + "channel_sid=\(self.channelsid!)&author=\(self.userid!)&message=\(inputMessage)"
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),let url = URL(string: encoded)
{
print("notify url is",url)
AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}
You user parameters like url and it's wrong way to make request like this.
You need add parameters on request method like parameters. And yes, you can use parameters on 'GET' requests.
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification"
let params:[String: Any] = ["channel_sid":self.channelsid!, "author":self.userid!, "message": inputMessage]
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded) {
print("notify url is",url)
AF.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}

how to use form data in Alamofire

In the postman in the body section in the form-data part when I pass a mobile number as a key and mobile number as Int value I get a response. But when I did it in the code I will not get the response as expected.
my code is
func fetchRegisterData(){
let url = registerApi
var mobileNumber = mobilenumberTextfield.text
let parameters = ["mobile" : mobileNumber] as [String : Any]
AF.request(url,method: .post, parameters: parameters, encoding:JSONEncoding.default).responseJSON
{ response in switch response.result {
case .success(let JSON):
print("response is :\(response)")
case .failure(_):
print("fail")
}
}
}
If you're trying to pass parameters as multipart/form-data you have to use the upload method in Alamofire:
func fetchRegisterData() {
let parameters = ["mobile": mobilenumberTextfield.text!]
AF.upload(multipartFormData: { (multiFormData) in
for (key, value) in parameters {
multiFormData.append(Data(value.utf8), withName: key)
}
}, to: registerApi).responseJSON { response in
switch response.result {
case .success(let JSON):
print("response is :\(response)")
case .failure(_):
print("fail")
}
}
}
For normal Alamofire request -
While passing values as a parameter in Alamofire Request. You need to know about the data type of the request type values which is valid for API.
At API end, these values are getting parsed based on some data types. There must be some validations on the data type at the API side.
for mobileNumber, it can be either Int or String
1 - let parameters = ["mobile" : mobileNumber] as [String : Int]
2 - let parameters = ["mobile" : mobileNumber] as [String : String]
For multipart form data request use have to use something like below. However, if you are not uploading anything you should not use it. Ask API team to make changes in the API and normal parameters request
Alamofire.upload(multipartFormData: { (multipartFormData) in
//Try this
multipartFormData.append(mobileNumber, withName: "mobile")
//or this
multipartFormData.append("\(String(describing: mobileNumber))".data(using: .utf8)!, withName: "mobile")
}, usingThreshold: 10 * 1024 * 1024, to: apiUrl, method: .post, headers: [:], encodingCompletion: { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
case .failure( _):
}
})

Swift Alamofire post "Extra argument in call"

I want to post some xml to an url. This is my code:
func post(){
var data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Devices><Device><ID>EZR0114AF</ID><HEATAREA nr=\"4\"><T_TARGET>17.0</T_TARGET></HEATAREA></Device></Devices>"
Alamofire.request(urlPost, .post, parameters: data, encoding: .utf8, headers: nil).response { (response) in
print(response.data)
print(response.error)
print(response.response)
}
}
But I get a Syntax error: Extra argument in call. I have no idea what is missing, I tried a lot but nothing works. Any ideas?
Try changing the syntax to
let urlString = "XXXXXXXXX"
Alamofire.request(urlString, method: .post, parameters: ["id": "1,2,3,4"] ,encoding: JSONEncoding.default, headers: nil).responseString {
response in
switch response.result {
case .success(let responseString1):
print("the response is: \(responseString1)")
break
case .failure(let error):
print("The error is: \(error)")
}
}

Alamofire photo upload with key of the file in body

I am able to upload a photo via Postman but in my iOS application it fails, and it is so weird that I still get a .success from encodingCompletion.
Here is part of my code
UpdateUserInfo
//
// Update user info
//
func updateUserInfo(){
var imageData: Data!
var url = ""
if let userId = KeychainWrapper.standard.string(forKey: USER_ID_KEY){
url = URL_USER_UPLOAD_PIC + userId
}
if pickedImage != nil{
imageData = UIImagePNGRepresentation(pickedImage)
//imageData = UIImageJPEGRepresentation(pickedImage!, 1.0)
}
let token = KeychainWrapper.standard.string(forKey: USER_LOGIN_TOKEN_KEY)!
let headers: HTTPHeaders = [
"Authorization": "Bearer \(token)"
]
if imageData != nil{
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: "fileset", fileName: "file.png", mimeType: "image/png")
}, to: url,
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
print("Donkey Success \(String(describing: upload.response?.statusCode))")
upload.responseString(completionHandler: { (response) in
debugPrint(response)
})
case .failure(let encodingError):
print(encodingError)
print("Donkey Fail")
}
})
}
}
and in my postman I have
Postman
My first question is why I am getting a .success if it fails to upload?
and my second question is, do I need to put the key "pic" (seen in Postman) somewhere in my request? if so where?
Thanks for any help in advance
In Post man Image Key is pic but in your code its "fileset"
change to
multipartFormData.append(imageData!, withName: "pic", fileName: "file.png", mimeType: "image/png")
And success is Result of encoding not uploading processs
EncodingResult is MultipartFormDataEncodingResult that Defines
whether the MultipartFormData encoding was successful and contains
result of the encoding as associated values. - Success: Represents a successful MultipartFormData encoding and contains the
new UploadRequest along with
streaming information. - Failure: Used to represent a failure in the MultipartFormData encoding and also
contains the encoding

Cannot get result while I use Alamofire

I am using Alamofire version 3.1.5 with my xCode version 7.3. I tried it on many apps of mine. But I do not get any result. No error is seen before the execution. My code is like this:
var apiUrl : String
var alamoFireManager:Manager!
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
init(apiUrl : String){
self.apiUrl = apiUrl
configuration.timeoutIntervalForRequest = 30.0
alamoFireManager = Alamofire.Manager(configuration: configuration)
}
print(apiUrl)
alamoFireManager.request(.GET, apiUrl, encoding: .JSON).validate(contentType: ["application/json"]) .responseJSON { response in
print(response.result.value)
switch response.result{
case .Success:
if let value = response.result.value{
let json = JSON(value)
print (json)
callback.onResponse(value) // this is where my value is sent
}
case .Failure(let error):
print(error.localizedDescription)
}
}
I checked using breakpoint and the app directly reaches this last braces frm the alamofire line.
I think the issue is you are not calling resume(). From the Alamofire doc
If the owning manager does not have startRequestsImmediately set to
true, the request must call resume() in order to start.
try this
alamoFireManager.request(.GET, apiUrl, encoding: .json).validate(contentType: ["application/json"]).resume().responseJSON { response in
print(response.result.value)
switch response.result{
case .Success:
if let value = response.result.value{
let json = JSON(value)
print (json)
callback.onResponse(value) // this is where my value is sent
}
case .Failure(let error):
print(error.localizedDescription)
}
}