Working with Alamofire - ios

Working with Alamofire, getting:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
2." error
Here is my code in NetworkClass:
class func requestPOSTURL(_ strURL : String, params :[String:String], success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
and request call:
let strURL = "myurl"
let parameters : [String: String] =
[
"user_name":"SNSH" as String,
"password":"SNOSH" as String,
"device_id":"0D4F5322-81C0-0000-9210-70DA0C6BC04C" as String,
]
if let json = try? JSONSerialization.data(withJSONObject: parameters, options: []) {
// here `json` is your JSON data, an array containing the String
// if you need a JSON string instead of data, then do this:
if let content = String(data: json, encoding: String.Encoding.utf8) {
// here `content` is the JSON data decoded as a String
print(content)
print(parameters)
NetworkClass.requestPOSTURL(strURL, params: parameters, success: {
(JSONResponse) -> Void in
print(JSONResponse)
}) {
(error) -> Void in
print(error)
}
}
}
I need to send String in parameters.

let urlAsString1 : String = API
let urlStr : NSString = urlAsString1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let params:NSMutableDictionary? = [
"user_name":"SNSH" as String,
"password":"SNOSH" as String,
"device_id":"0D4F5322-81C0-0000-9210-70DA0C6BC04C" as String,
];
let ulr = NSURL(string:urlStr as String)
let request = NSMutableURLRequest(URL: ulr!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! NSJSONSerialization.dataWithJSONObject(params!, options: NSJSONWritingOptions.PrettyPrinted)
let json = NSString(data: data, encoding: NSUTF8StringEncoding)
if let json = json {
print(json)
}
request.HTTPBody = json!.dataUsingEncoding(NSUTF8StringEncoding);
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch (response.result) {
case .Success(let JSON):
print("JSON: \(JSON)")
let responseString = JSON as! NSDictionary
print(responseString)
break;
case .Failure:
break
}
}
}

Related

Issue while sending array of dictionary in swift

I am creating array of dictionaries and then passing that in paramDictionary and sending to server but I get responseStatus code 422. I am using Alamofire 5.
Here is the structure of param which I have to send and it successfully working on postman but in app it is always fails
{"check_in": [{"check_in_at":"2020-02-26 03:23:44", "gps_coordinates":"3.1697998046875,101.61672197976593"},
{"check_in_at":"2020-02-26 03:23:45","gps_coordinates":"3.1697998046875,101.61672197976593"}]}
Here is my code
func postCheckInApi(viewController: UIViewController,
completion:#escaping (_ result:SuccessErrorData)->(),
errorHandler:#escaping (_ result:Error,_ statusCode:Int?)->()//error handler
) {
let url = KCheckin
let geoArr = Constant.getSearchLocationHistory() ?? [GeoTaggingEntity]()
var arr = [[String: String]]()
for i in geoArr{
let dict: [String : String] = ["gps_coordinates" : i.gps_coordinates ?? "", "check_in_at" : i.check_in_at]
arr.append(dict)
}
let parameterDictionary = ["check_in": arr] as [String : Any]
print(parameterDictionary)
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": Constant.getBearerToken() ?? ""
]
AF.request(url, method: .post, parameters: parameterDictionary, headers: headers).responseData { response in
switch response.result{
case.success(let data):
do{
let jsonData = try JSONDecoder().decode(SuccessErrorData.self, from: data)
print("Success")
completion(jsonData)
}
catch{
//viewController.navigationController?.popToRootViewController(animated: true)
}
case .failure(let error):
print(error)
}
}
}
You can not add Array as parameter object to your paramDictionary. You need to covert your Array to json string and then add it to you paramDictionary.
For that use below Collection extension to convert your Array to Json String
extension Collection {
func json() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
}
How To Use
let jsonStr = yourArray.json()
add this jsonStr to your paramDictionary

Alamofire file upload getting error "JSON text did not start with array or object and option to allow fragments not set"

Below is my code referring this question answer
func createRequest(ResumeID: String, CandidateID: String, MediaName: String, FileExtension : String, MediaType : String) throws -> URLRequest {
let parameters = NSDictionary(objects: [ResumeID, CandidateID, MediaName, FileExtension,MediaType], forKeys: ["ResumeID" as NSCopying, "CandidateID" as NSCopying, "MediaName" as NSCopying, "FileExtension" as NSCopying, "MediaType" as NSCopying])
let boundary = generateBoundaryString()
let url = URL(string: "http://192.168.1.29/ColorsKit_New_Svr/WTCSvr.svc/WTCService?Id=6&SPName=Usp_RTN_IU_CandidateSubmissionResume")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let path1 = Bundle.main.path(forResource: "dummy-pdf_2", ofType: "pdf")!
request.httpBody = try createBody(with: parameters as? [String : String], filePathKey: "MediaContent", paths: [path1], boundary: boundary)
return request
}
private func createBody(with parameters: [String: String]?, filePathKey: String, paths: [String], boundary: String) throws -> Data {
var body = Data()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
}
for path in paths {
let url = URL(fileURLWithPath: path)
let filename = url.lastPathComponent
let data = try Data(contentsOf: url)
let mimetype = mimeType(for: path)
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n\r\n")
body.append(data)
body.append("\r\n")
}
body.append("--\(boundary)--\r\n")
return body
}
func sendMultipartRequest() {
let request: URLRequest
do {
request = try createRequest(ResumeID: "1", CandidateID: "1241124", MediaName: "dummy-pdf", FileExtension: "pdf", MediaType: "pdf")
} catch {
print(error)
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
// handle error here
print(error!)
return
}
// if response was JSON, then parse it
do {
let responseDictionary = try JSONSerialization.jsonObject(with: data!)
print("success == \(responseDictionary)")
// note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
//
// DispatchQueue.main.async {
// // update your UI and model objects here
// }
} catch {
print(error)
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
}
task.resume()
}
The Response I'm getting is:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.} responseString =
Optional("No Records Found")
This is strange because Postman is giving correct response. Means there is something missing in the code only :(
Use Alamofire
let upload_url = "your url"
let fieldName = "UploadedFile"
let mimeType = "plain/text"
Alamofire.upload(multipartFormData: { multipartFormData in
//you can add multiple file
multipartFormData.append(fileData as Data, withName: fieldName, fileName: fileName, mimeType: mimeType)
}, to: upload_url, method: .post, headers: ["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let _ = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
debugPrint("uploaderService error:\(encodingError)")
}
})
Use JSONSerialization as below
if let responseDictionary = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
...
}

code optimization not working in ios Swift?

I am using Swift and alamofire.
How can I do code optimization? This is my post and put request for different api's:
func getPDataFromURL(_ onCompletion:#escaping (Dictionary<String, Any>)-> Void)
{
let token = UserDefaults.standard.string(forKey: "UserLoginToken")
let Usertype = UserDefaults.standard.string(forKey: "Usertype")
let Userbranchid = UserDefaults.standard.string(forKey: "Userbranchid")
let UrlStraing = FETCH_Parent_Profile_URL
print(UrlStraing)
let url = URL(string: UrlStraing)!
var urlRequest = URLRequest(url:url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let userToken = "Token token=" + token! as String
urlRequest.addValue(userToken, forHTTPHeaderField: "Authorization")
Alamofire.request(urlRequest).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
onCompletion(response.result.value! as! Dictionary<String, Any>)
}
break
case .failure(_):
print(response.result.error!)
onCompletion(response.result.error as! Dictionary<String, Any>)
break
}
}
}
And this is my second post request for another api:
func getSDataFromURL(_ onCompletion:#escaping (Dictionary<String, Any>)-> Void) {
let token = UserDefaults.standard.string(forKey: "UserLoginToken")
let Usertype = UserDefaults.standard.string(forKey: "Usertype")
let Userbranchid = UserDefaults.standard.string(forKey: "Userbranchid")
let UrlStraing = FETCH_School_Info_URL + "branch_id=" + Userbranchid! + "&student_id=86&user_type=" + Usertype!
print(UrlStraing)
let url = URL(string: UrlStraing)!
var urlRequest = URLRequest(url:url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let userToken = "Token token=" + token! as String
urlRequest.addValue(userToken, forHTTPHeaderField: "Authorization")
Alamofire.request(urlRequest).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
onCompletion(response.result.value! as! Dictionary<String, Any>)
}
break
case .failure(_):
print(response.result.error!)
onCompletion(response.result.error as! Dictionary<String, Any>)
break
}
}
}
And calling function in viewcontroller like this:
func SetUpSchoolUIProfiledata() {
Common.sharedInstance.StartActivity(view: self.view)
DispatchQueue.main.async {
APIManager.sharedInstance.getSchoolProfileDataFromURL(){(userJson)->
Void in
self.stop()
let swiftyJsonVar = JSON(userJson)
print("userJson userJson userJson userJson",userJson)
print("swiftyJsonVar",swiftyJsonVar)
let message = swiftyJsonVar["message"].rawString()
let info = swiftyJsonVar["info"].rawString()!
let jsonData = info.data(using: .utf8)!
let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>
self.schoolName_lbl.text = dictionary?["name"] as? String
self.add1_lbl.text = dictionary?["add_line1"] as? String
print("imgURLstring is ",self.imgURLstring)
self.SetUpProfileImage()
}
}
}
how to create single function multiple post and get requests?
You can create singleton class like this
when you want to call the web service, use this method
class DataProvider: NSObject {
class var sharedInstance:DataProvider {
struct Singleton {
static let instance = DataProvider()
}
return Singleton.instance
}
let baseUrl:String = "http://192.168.1.25:3004/api3/v3/"
func putData( parameter:[String:String], url:String, _ successBlock:#escaping ( _ response: JSON )->Void , errorBlock: #escaping (_ error: NSError) -> Void ){
let path = baseUrl + url
print(path)
print(parameter)
let headers = ["authorization": AppData().token]
Alamofire.request(path, method: .put, parameters: parameter, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
if let value = response.result.value {
let json = JSON(value)
successBlock(json)
}
case .failure(let error):
errorBlock(error as NSError)
}
}
}
call like this
DataProvider.sharedInstance.putData(parameter: parameter, url: "users/account/update", { (response) in
print(response)
if response["status"].stringValue == "200" {
Utility.showMessageDialog(onController: self, withTitle: "", withMessage: response["message"].stringValue)
}
}) { (error) in
print(error)
}

POST Json to API with Alamofire?

I want to post a JSON object I create in my service class and pass to the networkService.
This is my network service, but i get an error of
Value of type '[String : Any]' has no member 'data'
on the line: let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
func request(json: [String:Any]) {
let url = URL(string: urlString)!
let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
}
The idea being I pass in my JSON when i call the func via the func parameter.
This is the JSON object passed in:
func loginUser(data: Array<String>, deviceToken: String) {
// create JSON
let json = [ "login-email" : data[0],
"login-password" : data[1],
"login-secret" : "8A145C555C43FBA5",
"devicetoken" : deviceToken
]
networkManager.request(json: json)
}
Then I convert and send it to the API (urlString)
Any idea if/why this isnt working?
THanks
Updated revision:
func request(json: [String:Any]) {
let url = URL(string: urlString)!
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options:[])
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
} catch {
print("Failed to serialise and send JSON")
}
}
update: added my code to make a call with completion question:
func sendLoginRequest() {
let userLogin = UserService.init(loginEmail: userEmail, loginPassword: userPassword, loginSecret: loginSecret, deviceToken: deviceToken)
networkService.logUserIn(request: userLogin) { (<#JSON?#>, <#NSError?#>) in
<#code#>
}
}
edit: Updated Payload Shot:
edit 2: mapping issue example:
init?(_ json: JSON) {
// Map API Key from top level
guard let apiKey = json["apikey"].string else { return nil }
// Map User at user level
guard let userDataArray = json["user"].array else {
fatalError("user data array NOT FOUND")
}
print("USER DATA IS \(userDataArray)")
// assign user
for child in userDataArray {
guard let userID = child["id"].int,
let userEmail = child["email"].string,
let lastName = child["lastname"].string,
let firstName = child["firstname"].string,
let company = child["company"].string,
let userImage = child["image"].string,
let jobTitle = child["jobtitle"].string
else { return nil
}
}
// Assign to model properties
self.apiKey = apiKey
self.userEmail = userEmail
self.lastName = lastName
self.firstName = firstName
self.company = company
self.userImage = userImage
self.jobTitle = jobTitle
self.userID = userID
}
I just show how I work with this.
You don't have to convert your parameters to JSON. It's code from Alamofire.
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
Use this method instead of your:
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
Try this:
Instead of your request.httpBody = jsonData you can pass your json in parameters.
Your whole code will be:
func request(json: [String:Any]) {
Alamofire.request(urlString, method: .post, parameters: json, encoding: JSONEncoding.default).responseJSON {
(response) in
print(response)
}
}
If you are interested in my approach:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
let parameters = request.converToParameters()
Alamofire.request(Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
Request:
struct MakePickRequest: GeneralRequest {
let eventId: Int64
let sportId: String
let pickType: PickType
let betType: BetType
let amount: Int
func converToParameters() -> [String : String] {
return ["event_id": String(eventId), "sport_id": sportId,
"pick_type": pickType.rawValue, "bet_type": betType.rawValue,
"amount": String(amount)]
}
}
Structure with endpoints:
struct Endpoints {
// Development baseURL
static let baseURL = "http://myurl/"
private static let apiVersion = "api/v1/"
static var fullPath: String {
return "\(baseURL)\(apiVersion)"
}
// MARK: - User endpoints (POST)
static var login: String {
return "\(fullPath)users/login"
}
static var signUp: String {
return "\(fullPath)users/signup"
}
...
}
Outside of any class (but import SwiftyJSON is obligatory):
typealias APICompletionHandler = (_ data: JSON?, _ error: NSError?) -> Void
Handle response:
private func handleResponse(response: DataResponse<Any>, completionHandler: APICompletionHandler) {
self.printDebugInfo(response)
switch response.result {
case .success(let value):
self.handleJSON(data: value, handler: completionHandler)
case .failure(let error):
print(error)
completionHandler(nil, error as NSError?)
}
}
private func handleJSON(data: Any, handler: APICompletionHandler) {
let json = JSON(data)
let serverResponse = GeneralServerResponse(json)
if (serverResponse?.status == .ok) {
handler(serverResponse?.data, nil)
} else {
handler(nil, self.parseJsonWithErrors(json))
}
}
GeneralServerResponse (depends on your server API):
import SwiftyJSON
final class GeneralServerResponse {
let data: JSON
let status: Status
init?(_ json: JSON) {
guard let status = json["status"].int else {
return nil
}
self.status = Status(status)
self.data = json["data"]
}
enum Status {
case ok
case error
case unauthorized
init(_ input: Int) {
if input >= 200 && input < 400 {
self = .ok
} else if input == 403 {
self = .unauthorized
} else {
self = .error
}
}
}
}
My actual example of usage.
This is outside:
func +=<K, V> ( left: inout [K : V], right: [K : V]) { for (k, v) in right { left[k] = v } }
Example of request:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
var parameters = ["auth_token": Preferences.getAuthToken()]
parameters += request.converToParameters()
manager.apiRequest(url: Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
SessionManager extension to add headers for all requests:
extension SessionManager {
func apiRequest(url: URLConvertible, method: HTTPMethod, parameters: Parameters? = nil, encoding: ParameterEncoding, headers: HTTPHeaders? = nil) -> DataRequest {
var customHeaders: HTTPHeaders = ["api-key" : "1wFVerFztxzhgt"]
if let headers = headers {
customHeaders += headers
}
return request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
}
}
In APIManager class:
private let manager: SessionManager
init() {
manager = Alamofire.SessionManager.default
}
Call example:
apiClient.makePick(request: request) { data, error in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
// data is a JSON object, here you can parse it and create objects
}
}
Example of class:
import SwiftyJSON
final class MyClass {
let id: Int
let username: String
let parameter: Double
init?(_ json: JSON) {
guard let id = json["id"].int, let username = json["username"].string,
let parameter = json["parameter"].double else {
return nil
}
self.id = id
self.username = username
self.parameter = parameter
}
}

How to send json as parameter iOS swift?

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" : " "
]
]

Resources