Post arabic characters in almofire swift ios - ios

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()
}
}

Related

Access JSON value from Alamofire response

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
}
})

How to send form-data body with Alamofire [duplicate]

This question already has answers here:
Send POST parameters with MultipartFormData using Alamofire, in iOS Swift
(13 answers)
Closed 5 years ago.
I want to make a request wit Alamofire like this:
postman request
As you can see, i have a parameter called "data" and its value is a Json,
How can i do that using Alamofire?
I have tried with parameters, but doesnt wotk
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
Any suggestions?
UPDATE
Here is my code
var arrayProducts = [[String: String]]()
let product: [String: String] = ["qty": self.txtQty.text!, "precio": self.productPrice, "product_id": self.productId]
arrayProducts.append(product)
let parameters = [
"products": arrayProducts,
"address": self.userInfo["userAddress"]!,
"latitude": "6.157738",
"longitude": "-75.6144665",
"id": 1,
"name": self.userInfo["userName"]!,
"cellphone": self.userInfo["userPhone"]!,
"emei": "23456resdfty"
] as [String : Any]
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
when you have an Any Data as paremeter, you should sent the URLRequest to Alamofire, it supports Any as body
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
Alamofire.request(request)
.responseString { (response) in
// to do anything
}
Here is an example 4 you, the CURL statement an example of what it is doing.
Note token referenced here is a shared secret, obviously not stuff to post to SO :) bags of print statements in here so that you can see what going on/wrong :)
func files_download(sourcePath: String) {
// curl -X POST https://content.dropboxapi.com/2/files/download
// --header "Authorization: Bearer ab-XXX"
// --header "Dropbox-API-Arg: {\"path\": \"/acme101/acme1/acme.png\"}"
var headers:HTTPHeaders!
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token, "Dropbox-API-Arg": dataString!]
} catch {
print("Oh fudge")
}
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in
guard feedback.result.value != nil else {
print("Error: did not receive data", //rint("request \(request) feedback \(feedback)"))
return
}
guard feedback.result.error == nil else {
print("error calling POST on list_folder")
print(feedback.result.error)
return
}
if let JSON = feedback.result.value {
print("JSON: \(JSON)")
let dataString = String(data: JSON, encoding: .utf8)
print("JSON: \(JSON) \(String(describing: dataString))")
}
if let IMAGE = feedback.result.value {
print("downloaded \(sourcePath) \(sharedDataAccess.currentSN)")
sharedDataAccess.fnData(index2seek: sharedDataAccess.currentSN, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("previewPane"), object: nil, userInfo: nil)
}
})
}

Swift - How to send POST request with "x-www-form-urlencoded" content-type

I searched a lot and there's no clear instruction for sending POST request with "x-www-form-urlencoded" content-type.
i want to know how to do that and if you know how to do it with Alamofire it would be even better.
any help will be appreciated.
Hope you are searching for this one or give us more explanation in code so we get it easily:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
I used below code in swift 4.2
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
Try this following method using Alamofire
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.default)
If it doesn't work, which is unlikely, use this following code
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

how to post id and password by alamofire

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)")
}
}

Alamofire data send with HTTPBody issue

I'm trying to make api request with Alamofire. Data want to send with body. heare is what im doing.
let URL : String = "\(BaseUrl.sharedInstance.URL)\(EndPoint)"
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(RequestData, options: options)
let jsons = NSString(data: data, encoding: NSUTF8StringEncoding)
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
Alamofire.request(mutableURLRequest)
.response { request, response, data, error in
print(request)
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
print(response)
print(error)
}
} catch {
print("JSON serialization failed: \(error)")
}
anyone have idea about it.
Alamofire.request(.POST, URLString, parameters: parameters, encoding: .JSON, headers: headerss).responseJSON
{
response in switch response.result
{
case .Success(let JSON):
let response = JSON as! NSDictionary
print (response);
onSuccess (response)
//example if there is an id
case .Failure(let error):
onFailure (error);
print("Request failed with error: \(error)")
}
}

Resources