How to make PUT request in Alamofire in swift 4 - swift

I am new to swift and Alamofire, I had a data from services that we are publishing in tableviews, but there is an option for the user to edit the data displaying in tableviews. Edited data should update the service and publish edited new data to the tableviews.
Data from service:
[
{
"Id": 1,
"Name": "Sr",
"designation": "",
"officeLandLine": "456123789",
"officeMobile": "789456",
"officeEmail": "klm#mail.com",
"personalEmail": "",
"address": ""
},
{
"Id": 2,
"Name": "S",
"designation": "D",
"officeLandLine": "0863",
"officeMobile": "810",
"officeEmail": "dy#gov.in",
"personalEmail": "",
"address": ""
},

Please try this:
func serviceCallForUpdateData(withSelectedIndex index: Int){
let param = ["id" : self.arry[index].id, "name" : self.arry[index].name]
let requestURL = "your url"
print("***************************** URL: *********************************\(requestURL)")
Alamofire.request(requestURL, method: .put, parameters: param as? Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (responseJson) in
print("Response : \(responseJson)")
if (responseJson.result.isSuccess){
let dictRes = responseJson.result.value as! NSDictionary
completion(["res":dictRes, "stats":1] as AnyObject?)
} else {
let res : NSDictionary = ["msg":"Network Error"]
completion(["res":res, "stats":0] as AnyObject?)
}
}
}
call this function in didSelect method of table view.
You can get the data from the array didSelect method.
In dedSelect method please write:
self.serviceCallForUpdateData(index : indexPath.row)
It may helps you.Thank you.

Related

How to send data into post request parameters for the following JSON data?

I have checkboxes required for product return on a page with more than one product, and when I press a checkbox, I want to store the id and quantity of the selected product in the items in the post parameter that I want to send.But, I cannot send the correct data. How can I send correct data?
{
"reasonId" : "001",
"cancel" : "true",
"description": "" ,
"items": [
{
"id": "874a8064-bebf-41c3-98a8-6ac39a54156a",
"quantity" : 480
},
{
"id": "d7af8722-58cb-4bd0-9927-47de44ba2e0b",
"quantity" : 2
},
{
"id": "f799d66e-cfcd-4f2b-9603-1facf2fedbea",
"quantity" : 1
},
{
"id": "5ea0c31f-952a-4fbc-b623-9086030193ad",
"quantity" : 17
}
]
}
I can print the id and quantity of the selected product.
private func createCheckBox(_ model : OrderDetailItems, tag: Int) -> UIView {
let rootView = UIView()
returnItemCount = model.definition?.count
var checkBox: ViewCheckLabel!
checkBox = ViewCheckLabel(text: "",
range: "",
action: {
// CHECKK SELECT OR NOT SELECT
checkBox.buttonCheck.checkboxAnimation {
if checkBox.buttonCheck.isSelected {
print(model.quantity)
print(model.id)
} else {
}
}
})
This is my post request
func cancelOrderApi() {
if let parentVC = parentViewController as? MyProfileViewController {
parentVC.startActivityIndicator(mainView: parentVC.view)
let parameters : Parameters = [
"reasonId" : reasonId,
"cancel" : isOrdrReturnable,
"description": "",
"items" : ""
]
NetworkLayer.request(Router.returnOrder(parameters, orderReturnId ?? "")).responseDecodable(of: OrderCancel.self) { (response) in
switch response.result {
case .failure(let error):
Logger.shared.debugPrint("Error while fetching tags: \(String(describing: error))")
return
case .success(let response):
if response.code == 200 {
parentVC.showAlert(mesg: response.message ?? "Siparişiniz İade edilmiştir", title: "Başarılı")
} else {
parentVC.showAlert(mesg: response.message ?? "", title: "Hata")
Logger.shared.debugPrint(response.message ?? "")
}
Logger.shared.debugPrint(response)
}
DispatchQueue.main.async {
parentVC.stopActivityIndicator()
parentVC.profileTableView.reloadData()
}
}
}
}
I am not entirely sure what you want to achieve, since the question is unclear, however here is a tip how to create Data object (can be later inserted into Url request) from your JSON file. Firstly manually copy your JSON file somewhere to your project and give it name yourJSONFile , then you can create Data object with create createDataFromJson() function.
func createDataFromJson() -> Data? {
if let path = Bundle.main.path(forResource: "yourJSONFile", ofType: "json") {
do{
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
return data
} catch {
print("catched : \(error.localizedDescription) ❌")
return nil
}
} else {
return nil
}
}

Send JSON array as a parameter Alamofire

I'm having difficulty with a parameter which contains a Json array using Alamofire
Here is a string of my Json:
"[{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}]"
Here is my code where I make the request:
let data = (params["cart"] as! String).data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .fragmentsAllowed) as? [Dictionary<String, Int>] {
let parameters: Parameters = [
"address_id": params["address_id"] as! Int,
"delivery_day": params["delivery_day"] as! String,
"delivery_hour": params["delivery_hour"] as! Int,
"cart": jsonArray,
"via": params["via"] as! String
]
Alamofire.request(Global.baseURL + "orders/finish", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseSwiftyJSON {
Printing out my parameters
["cart": [["id": 546836102, "count": 1], ["count": 1, "id": 216479424]], "address_id": 641589205, "delivery_day": "1399-01-20", "delivery_hour": 21, "via": "ios"]
Backend must receive the cart as below:
[
{
"id": 123456,
"count": 2
},
{
"id": 654321,
"count": 3
}
]
But instead it gets the data like this:
{
"delivery_hour" : "21",
"delivery_day" : "1399-01-20",
"cart" : [
{
"count" : "1"
},
{
"id" : "546836102"
},
{
"count" : "1"
},
{
"id" : "216479424"
}
],
"via" : "ios",
"address_id" : "641589205"
}
I have tried JSONEncoding and URLEncoding options by Alamofire but nothing seems to work and this is the closest I've gotten to the API template so far.
What am I doing so wrong here?
// MARK: - Update
So I updated to the latest version of Alamofire and still no good results :(
Here is the code:
let payload = MyParameters(address_id: 641589205, delivery_day: "1399-01-21", delivery_hour: 21, cart: items, via: "ios")
AF.request(url, method: .post, parameters: payload, encoder: JSONParameterEncoder.default, headers: .init(header), interceptor: nil).response { dataResponse in
switch dataResponse.result {
case .success(let value):
if dataResponse.response?.statusCode == 200 {
let json = JSON(value!)
completionHandler(json, nil)
} else {
print(dataResponse.response?.statusCode ?? -1)
}
case .failure(let error):
print(error)
completionHandler(nil, error.localizedDescription)
}
}
My payload looks exactly what I want it to be
{
"cart" : [
{
"count" : 1,
"id" : 546836102
},
{
"count" : 1,
"id" : 216479424
}
],
"via" : "ios",
"address_id" : 641589205,
"delivery_day" : "1399-01-21",
"delivery_hour" : 21
}
But then again the endpoint receives this:
{
"{\"delivery_day\":\"1399-01-21\",\"address_id\":641589205,\"delivery_hour\":21,\"cart\":" : {
"{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}" : null
}
}
Using Alamofire 4, you can't send arrays using the method you've shown, as the Parameters type is [String: Any]. You're also not using the correct ParameterEncoding. If you want to send a JSON body, you need to use the JSONEncoding. What you can do is manually serialize the array into a URLRequest and make that request using Alamofire.
Additionally, if you update to Alamofire 5, Encodable parameters are now supported, so you if you can define your parameters as an Encodable type, sending them would be as easy as passing an array.
AF.request(..., parameters: [some, encodable, values], encoder: JSONEncoder.default)...

Trying to make the search bar functionality filter the names of the contacts which are coming from a json object into an array of strings

Want to convert my json object into an array of just names so I can use the search bar to search for different names and filter it.
"data2": {
"id": 1,
"contacts": [
{
"name": "Molly",
"pictureUrl": "molly"
},
{
"name": "Cathy",
"pictureUrl": "molly"
},
{
"name": "Bob",
"pictureUrl": "bob"
},
{
"name": "Nick",
"pictureUrl": "clothes"
}
],
},
"error": 0,
"message": "Success"
This is the json file with the object:
var contact = [IndividualContact]()
init?(data2: Data) {
do {
if let json2 = try JSONSerialization.jsonObject(with: data2) as? [String: Any], let body = json2["data2"] as? [String: Any] {
if let contacts = body["contacts"] as? [[String: Any]] {
self.contact = ( contacts.map { IndividualContact(json2: $0) } )
//Expected: ["Molly", "Bob", "Cathy"]
}
}

how to send array parameter using alamofire

I'm trying to make a post request with a body array in swift using Alamofire
postman like
and here my code
class func storeEventContact(_ id:String, type_contact:String, user_id: Int, firstname:String, lastname: String,completionHandler:RequestCompletionHandler?){
let url = "\(Endpoints.BASE)\(Endpoints.INVITE_STORE)"
let params:NSMutableDictionary? = ["id": id,
"type_contact":type_contact,
"contacts": ["user_id" : user_id, "firstname" : firstname, "lastname" : lastname]]
self.postRequest(url: url, parameters: params as? [String : Any]) { (result, error) in
self.postRequest(url: url, parameters: params as? [String : Any]) { (result, error) in
if error != nil{
completionHandler?(result, error)
return
}
let baseResponse = Mapper<BaseResponse>().map(JSONObject: result)
if !baseResponse!.status{
completionHandler?(baseResponse, error)
return
}
completionHandler?(result, error)
}
}
}
You just need to define an array, you are almost there, just need an extra set of [] in your dictionary.
let params = ["id": id,
"type_contact":type_contact,
"contacts": [
[
"user_id": user_id,
"firstname": firstname,
"lastname": lastname
]]]

Can't store values from callback function into class variables : Swift

I have a callback function which retrieves stuff from a url however the information doesn't get stored into class variables.
var counts:Int?
var imagesComments : [NSArray] = []
loader.getFeed("1", completionHandler: { response in
if let dataArr = response["content"] as? NSArray{
for downloaded_images in dataArr{
if let image = downloaded_images as? NSDictionary{
let url = image["url"] as? String
// Get images and load into images
if let comments = image["comments"] as? NSArray{
dispatch_async(dispatch_get_main_queue()) {
self.imagesComments.append(comments)
}
}
self.loader.downloadImage(NSURL(string: self.baseUrl+url!)!, completionHandler: { response in
dispatch_async(dispatch_get_main_queue()) {
self.images.append(response)
self.pileView?.reloadContent()
}
})
}
}
}
})
After this code is run, I have a place where I print imagesComments and counts and both are empty/nil
JSON File:
{
"success": true,
"message": null,
"content": [{
"url": "6\/image_2.png",
"date_added": "2015-12-02 22:43:05",
"comments": ["Awesome Pic", "WOOHOOOOO THIS IS GREAT"],
"likes": []
}, {
"url": "2\/image_5.png",
"date_added": "2015-12-01 06:43:48",
"comments": ["EhHHHH"],
"likes": []
}]
}