How to send json as parameter iOS swift? - ios

I want to send following object as body parameter. But serialization is failing:
{
"StartAddress":"Colombo",
"EndAddress":"Kandy",
"DepartureAddress":"Kollupitiya, Colombo",
"ArrivalAddress":"Peradeniya, Kandy",
"CreatedDate":"2017-07-30",
"Date":"2017-07-30",
"Time":"2017-07-30",
"IsLadiesOnly":true,
"IpAddress":"fe80::8638:38ff:fec8:ea50%wlan0",
"Country":"Srilanka",
"VehicleId":"1129",
"StartLocation":[
6.9270974,
79.8607731
],
"EndLocation":[
7.2916216,
80.6341326
],
"Points":"k}gi#y{lf",
"Route":{
"Bounds":{
"NorthEast":[
7.2916216,
80.6341326
],
"SouthWest":[
6.9270974,
79.8607731
]
},
"Legs":[
{
"LegId":1,
"Distance":14904,
"Duration":1941,
"StartAddress":"Colombo",
"EndAddress":"Kadawatha",
"StartLocation":[
6.9270974,
79.8612478
],
"EndLocation":[
7.0011125,
79.95000750000001
],
"Ancestors":[
],
"Price":745
},
{
"LegId":2,
"Distance":63040,
"Duration":6209,
"StartAddress":"Kadawatha",
"EndAddress":"Kegalle",
"StartLocation":[
7.0011125,
79.95000750000001
],
"EndLocation":[
7.251436200000001,
80.3466076
],
"Ancestors":[
"Colombo"
],
"Price":3152
},
{
"LegId":3,
"Distance":38990,
"Duration":4430,
"StartAddress":"Kegalle",
"EndAddress":"Kandy",
"StartLocation":[
7.251436200000001,
80.3466076
],
"EndLocation":[
7.2901864,
80.6338425
],
"Ancestors":[
"Colombo",
"Kadawatha"
],
"Price":1950
}
]
},
"TotalPrice":"5847.0",
"SeatCount":1,
"Detour":1,
"Luggage":2,
"DetoursDescription":"10 Minutes",
"LuggageDescription":"Small Luggage",
"Notes":"new ride"
}
when I try to serialize it before send it gives an error:
'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization
dataWithJSONObject:options:error:]: Invalid top-level type in JSON
write'
func synchronusPostRequstWithHeadersJson(apiMethod:String, params:JSON, headers:[ String: String]) -> ResultModel {
let resultModel = ResultModel()
//create the url with URL
let url = URL(string: BASE_URL + apiMethod )!
let session = URLSession.shared
//// **** HERE IT FAILING *****////
let jsonData = try? JSONSerialization.data(withJSONObject: params)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
for item in headers {
request.addValue(item.value, forHTTPHeaderField: item.key)
}
let semaphore = DispatchSemaphore(value: 0)
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if(error != nil){
resultModel.ErrorType = .NO_INT
resultModel.JsonReslut = JSON.null
}else{
if let resp = response as? HTTPURLResponse{
if(resp.statusCode == 200){
if let jsonResult = JSON(data) as? JSON {
resultModel.ErrorType = .NO_ERROR
resultModel.JsonReslut = jsonResult
}
}else{
if let jsonResult = JSON(data) as? JSON {
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = jsonResult
}else{
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = JSON.null
}
}
}
}
semaphore.signal()
})
task.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return resultModel
}
How can i send that request?. Is it possible with alamofire?

Using Almofire you can achieve this as
let params: [String: Any] = [
"StartAddress":"Colombo",
"EndAddress":"Kandy",
"DepartureAddress":"Kollupitiya, Colombo",
"StartLocation":[
6.9270974,
79.8607731
],
"EndLocation":[
7.2916216,
80.6341326
],
] //Do check your dictionary it must be in correct format
Alamofire.request("yourUrl", method: .post, parameters: params, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
}

try using:
let session = Foundation.URLSession.shared
let url = URL(string: "Your server url")
var request = URLRequest(url : url!)
request.httpMethod = "POST"
let params :[String:Any] = ["name":"yuyutsu" as Any,"rollno":12 as Any] //Add your params
do {
let jsonData = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
session.dataTask(with: request, completionHandler: { data, response, error in
OperationQueue.main.addOperation {
guard error == nil && data != nil else { // check for fundamental networking error
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
// print("response = \(response)")
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString!)")
if let responsedata = responseString!.data(using: String.Encoding.utf8)! as? Data{
do {
let jsonResult:NSDictionary = try JSONSerialization.jsonObject(with: responsedata, options: []) as! NSDictionary
print("Get The Result \(jsonResult)")
if error != nil {
// print("error=\(error)")
}
if let str = jsonResult["success"] as? NSNull {
print("error=\(str)")
}
else {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Response string : \(responseString)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}) .resume()
}catch {
// print("Error -> \(error)")
}
hope this might help you out.

Creating JSON parameters to send it as a post body:
Function:
//MARK:- Create JSON String
func createJSONParameterString(postBody:AnyObject) -> String {
if let objectData = try? JSONSerialization.data(withJSONObject: postBody, options: JSONSerialization.WritingOptions(rawValue: 0)) {
let objectString = String(data: objectData, encoding: .utf8)
return objectString ?? ""
}
return ""
}
Usage:
var postBody = [AnyHashable:Any]()
postBody["device_id"] = "device_ID"
let parameters = createJSONParameterString(postBody: postBody as AnyObject)
print(parameters)

i have solved similar problem using Alamofire and SwiftyJson as follow
let call your object (data )
let json = JSON(data)
let Params :Dictionary = json.dictionaryObject!
and in Alamofire request
Alamofire.request(url, method: .post, parameters: Params , encoding: JSONEncoding.prettyPrinted, headers: nil)
//.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
case .success(let value):
}
it need to replace this "{ }" with "[ ]"
and alamofire and swift json handle that issue
ex:
[
{
"firstName" : " " ,
"lastName" : " "
},
{
"firstName" : " " ,
"lastName" : " "
}
]
change it to
[
[
"firstName" : " " ,
"lastName" : " "
],
[
"firstName" : " " ,
"lastName" : " "
]
]

Related

Passing an array of parameters as a request body in swift

I'm trying to pass an array of parameters that looks like this:
{
"watermarks": [
{
"email" : "correo_user",
"event_type" : "app",
"watermark" : "marcaAgua",
"date" : "date",
"location" : "location",
"segment" : 1,
"time" : "time",
"country" : "country",
"city" : "city"
}
]
}
I don't know how to pass it as an array of objects because I have never done it before. This is the code that I'm currently using:
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
print("QQQQQ")
print(unwrappedData)
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse as! Error))
}
}catch{
print("AAA")
completion(.failure(error))
}
}
}
}
task.resume()
}
When I pass the parameters to the function when I call it, I pass them as a dictionary of type [String:Any]. This is an example of it:
let signupQueryData : [String : Any] = [
"watermarks": [
"email" : correo_user as String,
"event_type" : "app" as String,
"watermark" : marcaAgua as String,
"date" : "\(dateActual) \(hour):\(minutes)" as String,
"location" : latitudYLongitud as String,
"segment" : 1 as Int,
"time" : "\(hour):\(minutes)" as String,
"country" : "\(qlq)" as String,
"city" : "Caracas" as String
]
]
And this is what it prints of parameters in the function marcaAgua:
["watermarks": ["time": "22:10", "segment": 1, "location": "location", "email": "mail", "event_type": "app", "watermark": "e356eaadcb3aa4a1049441fc48d83a22", "date": "13.07.2021 22:10", "country": "Venezuela", "city": "Caracas"]]
When I do that, I get the following error:
failure(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})
Try do like this
func marcaAgua(parameters: [String: Any],
completion: #escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
completion(.failure(errorResponse as! Error))
}
}catch{
completion(.failure(error))
}
}
}
}
task.resume()
}
initialise Variables
var invitationsArray = Array<[String: Any]>()
var invitations = Array<[String: Any]>()
Logic
invitations = [["friend_id": "\(each.friendId!)", "invited_type": "friend"]]
invitationsArray.append(contentsOf: invitations)
Set variables
let params: [String: Any] = [
"user_id":Global.shared.currentUserLogin.id,
"ride_name": planARide.name!,
"ride_description": planARide.description!,
"ride_type": planARide.rideType!,
"ride_date_and_time": planARide.rideDate!,
"ride_city": planARide.city!,
"ride_meeting_spot": planARide.rideMeetingSpot!,
"ride_meeting_latitude": planARide.latitude!,
"ride_meeting_longitude": planARide.longitude!,
"ride_intensity": planARide.rideIntensity!,
"time_length_of_ride": planARide.rideTime!,
"reoccuring_ride": planARide.rideReccurring!,
"special_instructions": planARide.specialInstruction!,
"open_ride_to_biking_community": planARide.openRideToBikingCommunity!,
"invitations": invitationsArray
]

statusCode should be 2xx, but is 400 in swift

I have a login API and use URLSession to hit API but I get the status code 400, here's my code -
let deviceType = "IOS"
let deviceToken = "654321"
#IBAction func onClickLogIn(_ sender: Any) {
guard let email = self.emailTf.text else {
return
}
guard let password = self.pwdTf.text else {
return
}
let url = URL(string: "http://example/api/login")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"username": email,
"password": password,
"deviceType" : deviceType,
"deviceToken" : deviceToken
]
request.httpBody = parameters.percentEncoded()
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else {
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else {
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}.resume()
}
when I use the breakPoints and type PO request.httpBody then it shows nil in httpBody and gets the status code 400 please anyone help me where I make the mistake
Set response data base type:
"application/x-www-form-urlencoded","multipart/form-data","application/json","text/plain","text/xml"
Ask your backend developer about API type ,is it From data api or Raw Json Api.based on that you have to do Coding.
you written for form data
so here is post api with raw json Api implementation
let parameters: [String: AnyObject] = [
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List": [
[
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
],
[
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
]
] ]
Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
.responseJSON { request, response, JSON, error in
print(response)
print(JSON)
print(error)
}

How to parse this JSON response in Swift

I usually use this code to parse most of JSON responses
Before the code, here the JSON I need to get form it the "workspace"
{
"count": 1,
"next": null,
"previous": null,
"results": [{
"id": 307,
"email": "999#ios.net",
"firstName": "fighter",
"categories": [],
"workspace": 302,
"phone": "25485"
}]
}
here is my code:
func getWorkSpace() {
DispatchQueue.main.async {
let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
print("UserDefaults Returned Access Token is: \(returnAccessToken!)")
let access = returnAccessToken!
let headers = [
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://v5/workspaces/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print("--------")
print(responseString)
print("--------")
DispatchQueue.main.async {
do {
let json = try JSON(data: data!, options: .allowFragments)
let answer = json["results"]
let workspace = Int(answer["workspace"].int!)
// let workspace = Int(answer["workspace"].string!)!
// let workspace = answer["workspace"].int!
print("Workspace is: \(workspace)")
} catch {
print("Error saving workspace!")
}
}
}
}
})
dataTask.resume()
}
}
This code usually works for me, but this time it's not. Please don't suggest me to use Codables because I didn't learn them yet.
SwiftyJSON
do {
let json = try JSON(data: data1!)
let answer = json["results"].array
answer?.forEach {
print($0["workspace"].int!)
}
} catch {
print("Error saving workspace!")
}
JSONSerialization
let json = try! JSONSerialization.jsonObject(with:data, options :[]) as! [String:Any]
let results = json["results"] as! [[String:Any]]
results.forEach {
print($0["workspace"] as! Int)
}
Codable
struct Root : Codable {
let results:[Model]
}
struct Model: Codable {
let id: Int
let email, firstName: String
let workspace: Int
let phone: String
}
let res = try! JSONDecoder().decode(Root.self, from:data)
print(res.results)

send multi part form data in swift

I used this code below to send multipart params
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer \(myToken)",
"cache-control": "no-cache"
]
let parameters = [
[
"name": "firstname",
"value": "alex"
],
[
"name": "lastname",
"value": "black"
],
[
"name": "birthdate_day",
"value": "1"
],
[
"name": "birthdate_month",
"value": "5"
],
[
"name": "birthdate_year",
"value": "1989"
],
[
"name": "gender",
"value": "m"
],
[
"name": "avatar",
"fileName": "\(imageURL)"
]
]
let boundary = "Boundary-\(NSUUID().uuidString)"
var body = ""
let error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
if let contentType = param["content-type"] {
do {
let fileContent = try String(contentsOfFile: filename, encoding: String.Encoding.utf8)
if (error != nil) {
print(error as Any)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} catch {
print(error)
}
}
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let postData = NSMutableData(data: body.data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "myUrl")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse?.statusCode as Any)
}
})
dataTask.resume()
return dataTask
the image url and the rest of the data But I will receive Satus code 500 I know that this error is server side But the android version is using the same api url and that's working well I know that this code can be fix and maybe small changes can fix this code for working
use URL instead of NSURL
var request = URLRequest is mutable, use this instead of NSMutableURLRequest
var data = Data() is mutable, use this instead of NSMutableData
append the file blob data safely using Data(contentsOf:options:) method
content-type is missing in parameters, so if let contentType = param["content-type"] { ... } will fail to proceed, using application/octet-stream default mime type
depending on the server, it might be necessary to provide a filename for the uploads
I fixed all above concerns and moved the URLRequest.httpBody generating code to following extension.
extension URLRequest {
private func formHeader(_ name: String, crlf: String, fileName: String? = nil, mimeType: String? = nil) -> String {
var str = "\(crlf)Content-Disposition: form-data; name=\"\(name)\""
guard fileName != nil || mimeType != nil else { return str + crlf + crlf }
if let name = fileName {
str += "; filename=\"\(name)\""
}
str += crlf
if let type = mimeType {
str += "Content-Type: \(type)\(crlf)"
}
return str + crlf
}
private func getFileUrl(_ file: Any) -> URL? {
if let url = file as? String {
return URL(string: url)
}
return file as? URL
}
private func getFileData(_ url: URL) -> Data? {
do {
return try Data(contentsOf: url, options: .mappedIfSafe)
} catch {
print(error)
return nil
}
}
mutating func setPost(body parameters: [[String: Any]]) {
let boundary = "Boundary+\(arc4random())\(arc4random())"
self.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
data.append("--\(boundary)".data(using: .utf8)!)
let crlf = "\r\n"
for parameter in parameters {
guard let paramName = parameter["name"] as? String else { continue }
if let value = parameter["value"] {
let header = formHeader(paramName, crlf: crlf)
data.append("\(header)\(value)".data(using: .utf8)!)
} else if let file = parameter["file"], let fileUrl = getFileUrl(file), let fileData = getFileData(fileUrl) {
let fileName = parameter["fileName"] as? String
let contentType = parameter["content-type"] as? String
let header = formHeader(paramName, crlf: crlf, fileName: fileName ?? fileUrl.lastPathComponent, mimeType: contentType ?? "application/octet-stream")
data.append(header.data(using: .utf8)!)
data.append(fileData)
} else {
print("\(paramName): empty or invalid value")
continue
}
data.append("\(crlf)--\(boundary)".data(using: .utf8)!)
}
data.append("--\(crlf)".data(using: .utf8)!)
self.httpBody = data
self.httpMethod = "POST"
}
}
Usage
let parameters = [
["name": "firstname", "value": "alex"],
["name": "avatar", "file": URL],
["name": "avatar", "file": "file:///", "fileName": "image.png", "content-type": "image/png"]
]
request.setPost(body: parameters)
Note above in parameters
file key represents either a URL object or file path String.
fileName: image.png is for backend, represents name of the file.
Finally add headers and create URLSession.shared.dataTask as your original code.
Update-2 function instead of an extension
func getParameterData(_ name: String, parameter: [String : Any]) -> Data? {
var str = "\r\nContent-Disposition: form-data; name=\"\(name)\""
if let value = parameter["value"] {
return "\(str)\r\n\r\n\(value)".data(using: .utf8)!
}
guard
let file = parameter["file"],
let url = (file is String ? URL(string: file as! String) : file as? URL)
else {
return nil
}
let data: Data
do {
data = try Data(contentsOf: url, options: .mappedIfSafe)
} catch {
print(error)
return nil
}
let fileName = (parameter["fileName"] as? String) ?? url.lastPathComponent
str += "; filename=\"\(fileName)\"\r\n"
let contentType = (parameter["content-type"] as? String) ?? "application/octet-stream"
str += "Content-Type: \(contentType)\r\n"
return (str + "\r\n").data(using: .utf8)! + data
}
func setPostRequestBody(_ request: inout URLRequest, parameters: [[String: Any]]) {
let boundary = "Boundary+\(arc4random())\(arc4random())"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
data.append("--\(boundary)".data(using: .utf8)!)
for parameter in parameters {
guard
let name = parameter["name"] as? String,
let value = getParameterData(name, parameter: parameter)
else {
continue
}
data.append(value)
data.append("\r\n--\(boundary)".data(using: .utf8)!)
}
data.append("--\r\n".data(using: .utf8)!)
request.httpBody = data
}
Usage-2
var request = URLRequest(url: URL(string: "myUrl")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
setPostRequestBody(&request, parameters: [
["name": "firstname", "value": "alex"],
["name": "avatar", "file": URL object or path String]
])
let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
guard error != nil else {
print(error!.localizedDescription)
return
}
let statusCocde = (response as? HTTPURLResponse)?.statusCode
print(statusCode ?? 0)
if let data = data {
print(String(data: data, encoding: .utf8) ?? "")
}
}
dataTask.resume()

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

Resources