Alamofire parameter encoding, dictionary within a dictionary - ios

Want to send this to Alamofire using Swift...
curl -X POST https://content.dropboxapi.com/2/files/download
--header "Authorization: Bearer ab-xxx-x-x"
--header "Dropbox-API-Arg: {\"path\": "/acme101/acmeX100/acmeX100.001.png\"}"
But can't figure how to get the second --header you see here into the code? Tried several times with different combinations, but ...
JSON: 114 bytes Optional("Error in call to API function \"files/download\": Must provide HTTP header \"Dropbox-API-Arg\" or URL parameter \"arg\".")
I provided it, but not correctly evidently?
let subPart: NSDictionary = ["path": sourcePath]
let headers:HTTPHeaders = ["Authorization": "Bearer " + token2Save, "Dropbox-API-Arg": String(describing: subPart)]
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in

Ureka!! THANK YOU Mr UB for giving me those tips. Found the solution.
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token2Save, "Dropbox-API-Arg": dataString!]
} catch {
print("crunch")
}
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", print("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) \(dataString)")
}
if let IMAGE = feedback.result.value {
sharedDataAccess.fnData(index2seek: 0, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("previewPane"), object: nil, userInfo: nil)
}
})

Related

Post arabic characters in almofire swift 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()
}
}

JSON data not parsing using with Alamofire in swift3

I have to parse json using alamofire
before am using json session its working fine getting data from the json. now am try to parse json using alamofire.
this is the code parse the json using json, this code working fine
func auth(_ email:String,password:String) {
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "email=\(email)&passCode=\(password)&deviceType=iOS&deviceId=\(deviceToken)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
do {
if data != nil {
if let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print(errorCode)
print(jsonData)
if(errorCode == "1"){
DispatchQueue.main.async(execute: {
self.activityIndicator.stopAnimating()
})
} else {
self.name = jsonData.value(forKey: "name") as! String
if let kidsURLDetails = jsonData["kidsURLDetails"] as? NSArray {
for i in 0 ..< kidsURLDetails.count {
if kidsURLDetails[i] is NSDictionary {
let url = kidsURLDetails[i] as? NSDictionary
self.urls.append((url?["url"]) as! String)
}
}
}
self.serverURL = self.urls.joined(separator: ",")
print("ServerURL \(self.serverURL)")
let prefs:UserDefaults = UserDefaults.standard
prefs.setValue(self.name, forKey: "NAME")
DispatchQueue.main.async(execute: {
UIApplication.shared.endIgnoringInteractionEvents()
let controllerId = "NavID"
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: controllerId) as UIViewController
self.present(initViewController, animated: true, completion: nil)
})
}
}
} else {
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
in above code I used post method with passing parameters, when I am trying post method with parameter passing in almofire am getting error "Extra argument 'method' in call", username and password coming from textfield so after enter the email and password I have pass the parameters using post method.
this is the code I will implemented in to alamofire json parse
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let bodyData = "email=\(username)&passCode=\(passcode)&deviceType=iOS&deviceId=123456"
let deviceId = "1234"
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
Alamofire.request(request, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
if I can try this code working
Alamofire.request("http://www.kids.com/rk/api/usersignin?email=demo#kidsapp.com&passCode=123456&deviceType=&deviceId=", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
how can I parse the json post method passing parameters using alamofire. where I did mistake pls help me
You are passing wrong type in 1 param in call it should be URLConvertible(string or URL) not URLRequest. try below code.
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let url = URL(string: "http://www.kids.com/rk/api/usersignin")!
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
}
____________Edit___________
here header is post request headers(if any) or nil
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let urlString = "http://www.kids.com/rk/api/usersignin"
guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: header) else{
//
return
}
request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
Alamofire.request(request).responseJSON { response in
}
If you need to send the parameters in url with post request you should use URLEncoding.default encoding rather than JSONEncoding.default. JSONEncoding is used when you need to send JSON data as body with content type application/json.
Change your code like:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { response in
print(response.result.value as Any)
}
Or you can remove encoding parameter as URLEncoding is the default encoding of Alamofire.
// URL
let urlString = “URL_Here”
var params = [String: Any]()
//Contruct your params
params = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
// Request
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.responseJSON { response in
if (response.result.error == nil) {
let value = response.result.value
print(value)
}
else {
let errorString = response.result.error
print(errorString)
}
}

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

Alamofire POST request not working

let requestDictionary : [String: AnyObject] = [
"sm_username" : name as AnyObject,
"sm_password" : pass as AnyObject
]
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded",
"Krikor": "Krikor"
]
Alamofire.request(baseURL+"login", method: .post, parameters: requestDictionary, encoding: JSONEncoding(options: []),headers: headers
).responseJSON{ response in
debugPrint(response)
print("krirkrkdkd")
print(response)
}
So basically, the headers are not being passed. Neither encoded parameters. Why? And how to fix?
Kiikor,
Here is a working example of a alamofire request in swift, including the encoding.
func files_download(sourcePath: String) {
let defaults = UserDefaults.standard
if let name = defaults.string(forKey: "dropBoxAuth")
{
token2Save = name
}
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 " + token2Save, "Dropbox-API-Arg": dataString!]
} catch {
print("error")
}
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", print("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 {
let dataString = String(data: JSON, encoding: .utf8)
}
if let IMAGE = feedback.result.value {
sharedDataAccess.fnData(index2seek: 0, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("nextACtion"), object: nil, userInfo: nil)
}
})

Alamofire 4 and special characters in JSON

I've got a problem with special characters with Alamofire 4.The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.Alamofire 4 shows something like this instead:
U00e6
Using this call:
Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in
print(response)
}
What to do to solve this?
Edit:
Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let value) :
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value as! [String:AnyObject]!{
print("JSON: ",JSON)
self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!
self.tableView.reloadData()
}
case .failure(let encodingError):
//Print error
}
}
I got the issue that I have added æ in json response and try to print.
Output:
JSON: Optional(<__NSArrayI 0x600000050320>(
{
"email_address" = "testwts06#gmail.com";
username = "testwts06 \U00e6";
},
{
"email_address" = "testwts01#gmail.com";
username = "testwts01 \U00eb";
},
{
"email_address" = "testwts100#gmail.com";
username = testwts100;
})
While displaying it display in correct format.
Swift 3 update for Ekta's answer:
let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.
JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.
You could try to convert the response data to correct UTF8 encoding:
let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue)
let data = datastring!.data(using: String.Encoding.utf8.rawValue)
do {
let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
let jsonDic = object as! NSDictionary
print(" ok, successfully converted..\(jsonDic)")
} catch let aError as Error {
// print and handle aError
}
Hope it helps you.
Here is a simple String extension that solves the issue:
extension String {
func fixUnicode() -> String {
var copy = self as NSString
let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()
matches.forEach {
let char = copy.substring(with: $0.rangeAt(1))
copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString
}
return copy as String
}
}

Resources