Swift Guy
Swift Guy

Reputation: 1395

How to fetch data from post method in Swift?

I have lists of data to be presented in tableview. The API works for POST method. But I don't get the data fetched on the tableview but it gets printed on the console. Can't we fetch data from POST method in Swift? Please help me to solve this problem.

import UIKit
import Alamofire

class SpendingsController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tblHome: UITableView!
    var dictData:NSArray = NSArray()
    var appDictionary:NSDictionary!
    var appDictionary2:NSDictionary!

    override func viewDidLoad() {
        super.viewDidLoad()

        tblHome.delegate = self
        tblHome.dataSource = self
        self.postData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dictData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath) as! SpendingsCell
        self.appDictionary = self.dictData.object(at: indexPath.row) as! NSDictionary
        cell.spend_receipt?.text =    self.appDictionary.value(forKey: "receipt_number") as? String
        cell.store_amount?.text =    self.appDictionary.value(forKey: "amount") as? String
        cell.spend_storename?.text =    self.appDictionary.value(forKey: "store_name") as? String
        return cell
        //Data are not fetched here.
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 156  //height for cell
    }

    func postData() {
        let headers = [
            "Authorization": "pZGFzbG9naW46QGRpZGFzJHRvcmU="   // its fake for privacy
        ]

        let todosEndpoint =  NSURL(string: "http://purchase_entries/Api/purchase_entry_list/")! as URL
        let USersIDs = UserDefaults.standard.object(forKey: "UsersId")

        let newTodo = ["user_id": USersIDs!]
        print(newTodo)
        Alamofire.request(todosEndpoint, method: .post, parameters: newTodo, encoding: URLEncoding.default, headers: headers)
            .responseJSON { response in
                debugPrint(response.result)

                if let JSON = response.result.value{
                    print("ion json",JSON)   // It prints the data
                    self.dictData = (JSON as AnyObject)["rows"] as! NSArray

                }
        }
    }
}

Upvotes: 0

Views: 1295

Answers (2)

Logic
Logic

Reputation: 705

i guess this is what you require :

   func callLoginWebService() {
        let token = SharedManager.getAuthenticationToken()
        let headers = [
            "token": token
        ]
        var params = [String:String]()
        params  = [
            "email":self.emailTxtField.text!,
            "password":self.passwordTxtField.text!]
        Alamofire.request(LoginUrl, method:.put, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            print("Request  \(String(describing: response.request))")
            print("RESPONSE \(String(describing: response.result.value))")
            print("RESPONSE \(response.result)")
            print("RESPONSE \(response)")

    }
    }

Save response.result.value to array or dictionary.Boom

Upvotes: 0

Mauli
Mauli

Reputation: 71

Make changes in your code:

 Alamofire.request(todosEndpoint, method: .post, parameters: newTodo, encoding: URLEncoding.default, headers: headers)

.responseJSON { response in debugPrint(response.result)

if let JSON = response.result.value{
  print("ion json",JSON)   // It prints the data
  self.dictData = (JSON as AnyObject)["rows"] as! NSArray
    if self.dictData.count > 0{
       DispatchQueue.main.async {
           yourTableView.reloadData()
      }
 }

}

Upvotes: 1

Related Questions