0

Please help as I have hit a road b lock with this issue. I have tried these URL1 & URL2 for guidance but haven't been successful.

How can I fix JSON which is not populating my UITableView

Here is my code:

class FilmsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    weak var tableView : UITableView!
    var FilmArray = [String]()

    let film_url = "https://www.testing.com/api/resources/films/1"
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Getting the right element
        //let films = FilmArray[indexPath.row]


        // Instantiate a cell
        //let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "moviecell")
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FilmsAPITableViewCell
        //        cell.movieTitle.text = FilmArray[indexPath.row]
        // Adding the right informations
        cell.movieTitle.text = FilmArray[indexPath.row]
        // Returning the cell
        return cell
    }
   // @IBOutlet weak var FilmsView: UITableView!
//    weak var tableView : UITableView!
//    var FilmArray = [String]()
//  
//    let film_url = "https://www.distribber.com/api/resources/films/1"
//    
    override func viewDidLoad() {
        super.viewDidLoad()

        let tableView = UITableView (frame:view.bounds)
        view.addSubview(tableView)
        self.tableView = tableView

        tableView.dataSource = self
        tableView.delegate = self


//        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//            return 1
//        }
//            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//                // Getting the right element
//               //let films = FilmArray[indexPath.row]
//                
//                
//                // Instantiate a cell
//                //let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "moviecell")
//                let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FilmsAPITableViewCell
//                //        cell.movieTitle.text = FilmArray[indexPath.row]
//                // Adding the right informations
//                cell.movieTitle.text = FilmArray[indexPath.row]
//                // Returning the cell
//                return cell
//        }
           // }

        //}



        let url:URL = URL(string: film_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("masked", forHTTPHeaderField: "X-API-KEY")
        request.setValue("masked=", forHTTPHeaderField: "Authorization")
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        let paramString = ""


        //        for (key, value) in post_data
        //        {
        //            paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
        //        }
        //
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }



            let json: Any?

            do
            {
                json = try JSONSerialization.jsonObject(with: data!, options: [])

               //  Prasing JSON
                var parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
                 print(parsedData)
                if let FilmArray = parsedData["films"] as? NSArray {
                    for movieTitle in FilmArray{
                        if let filmDict = movieTitle as? NSDictionary{
                            if let film = filmDict.value(forKey: "title") {
                            self.FilmArray.append(film as! String)
                            }

                            //OperationQueue.main.addOperation({
                              //self.FilmsView.reloadData()
                           // })

                        }
                    }

                }
              print("Hello")
               print(self.FilmArray)
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }


            if let data_block = server_response["data"] as? NSDictionary
            {
                if let session_data = data_block["session"] as? String
                {
                    //  self.login_session = session_data

                    let preferences = UserDefaults.standard
                    preferences.set(session_data, forKey: "session")

                    //  DispatchQueue.main.async(execute: self.LoginDone)
                }
            }



        })

        task.resume()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

["status": 1, "films": <__NSSingleObjectArrayI 0x7ae40320>(
{
    Stores =     (
                {
            Assets =             (
                                {
                    "asset_name" = Screener;
                    "asset_status" = Needed;
                },
                                {
                    "asset_name" = Feature;
                    "asset_status" = Needed;
                },
                                {
                    "asset_name" = Trailer;
                    "asset_status" = Needed;
                },
                                {
                    "asset_name" = Artwork;
                    "asset_status" = Needed;
                },
                                {
                    "asset_name" = "Closed Caption";
                    "asset_status" = Needed;
                },
                                {
                    "asset_name" = Meta;
                    "asset_status" = Needed;
                }
            );
            Status = Declined;
            "store_name" = "Netflix Watch <br> Instantly (SD)";
        }
    );
    title = "The Red Tail";
}
)
]

Please guide.

Community
  • 1
  • 1
  • 1
    Why are you nesting all of your functions? Don't do that. – rmaddy Feb 02 '17 at 03:08
  • _"I ... have been unsuccessful."_ - In what way? Does your code fail to compile? Does it crash? Does it produce incorrect behavior? Please provide details of the problem you are facing. – Ted Hopp Feb 02 '17 at 03:18
  • @rmaddy I have unnested them! Thanks for that!! – Kendell Rogers Feb 02 '17 at 03:36
  • @TedHopp it will not compile. I get the following error "Type 'FilmsViewController' does not conform to protocol 'UITableViewDataSource' – Kendell Rogers Feb 02 '17 at 03:38
  • You need to add the required functions from the `UITableViewDataSource` protocol. – rmaddy Feb 02 '17 at 03:39
  • @rmaddy Thanks man! Can you tell which ones I am missing? I could've sworn I've included them all. Sorry I am very new to Swift 3 or coding in general. – Kendell Rogers Feb 02 '17 at 03:42
  • You haven't included any of them because you've defined your overloaded functions inside `viewDidLoad()`. They need to be defined as methods of `FilmsViewController`. – Ted Hopp Feb 02 '17 at 03:45
  • Update your question's code with your properly unnested data source methods. Make sure you have the correct signature for them. – rmaddy Feb 02 '17 at 03:45
  • @rmaddy I have updated the question. – Kendell Rogers Feb 02 '17 at 03:58
  • @TedHopp where should I place them? Above viewdidload ? or after I'm done parsing the json? – Kendell Rogers Feb 02 '17 at 04:01
  • @rmaddy thank you guys for your help! It takes me a lot to ask for help now I'm regretting not reaching out sooner. – Kendell Rogers Feb 02 '17 at 04:02
  • They should appear at the top level of the class definition. They are called by the framework, not directly by your own code. – Ted Hopp Feb 02 '17 at 04:02
  • @TedHopp you too! I couldn't;t tag both of you in one post. As you can obviously tell I am new to this too! – Kendell Rogers Feb 02 '17 at 04:03
  • @TedHopp I will post my updated code. It now builds! But breaks before accessing the page. Went to new error now before loading page – Kendell Rogers Feb 02 '17 at 04:11
  • New error now! "Thread 1: signal SIGABRT" '2017-02-01 20:13:29.795 LoginScreenApp[39106:2445017] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key FilmsView.' *** First throw call stack: ( – Kendell Rogers Feb 02 '17 at 04:16
  • For that error see http://stackoverflow.com/questions/3088059/what-does-this-mean-nsunknownkeyexception-reason-this-class-is-not-key-v?s=1|15.3054 – rmaddy Feb 02 '17 at 04:23
  • @rmaddy someone submitted an answer but disappeared before I got to test it out? do you know how I can retrieve it? – Kendell Rogers Feb 02 '17 at 18:48
  • This question can be answered if you look at my answer in your other question: http://stackoverflow.com/a/42011798/2617369. I have updated the parsing logic and got this code to run successfully. – Prientus Feb 02 '17 at 22:34

0 Answers0