1

building my first iOS app here and I am stuck. I searched online and did not find anything about this particular issue.

Basically I have a UICollectionView displaying some data. Everything works fine on the simulator, but on the actual iPhone, it's like the UICollectionView is just not there.

No error messages and the app doesn't crash, and all the other elements of the App are functioning properly so I am quite perplexed.

Code:

//
//  SecondViewController.swift
//
//  Created by pc on 3/5/19.
//  Copyright © 2019 BF. All rights reserved.
//

import UIKit
import WebKit
import SwiftSoup

class SecondViewController: UIViewController, WKNavigationDelegate, UICollectionViewDataSource {


    @IBOutlet var dataTable: UICollectionView!
    @IBOutlet weak var viewHeader: UILabel!
    @IBOutlet weak var viewFooter: UILabel!

    @IBAction func backButtonClicked(_ sender: UIButton) {
        dismissVC()
    }


    var webView: WKWebView!
    var tableContent = [[String]]()
    var vSpinner : UIView?
    var testString = [[String]]()
    var submittedValue2: String = ""
    var currentSelection2: String = ""


    override func viewDidAppear(_ animated: Bool) {
        let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)

        let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.style = UIActivityIndicatorView.Style.gray
        loadingIndicator.startAnimating();

        alert.view.addSubview(loadingIndicator)
        present(alert, animated: true, completion: nil)

    }

    override func viewDidLoad() {
        super.viewDidLoad()


        self.dataTable.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        //dataTable.backgroundColor = UIColor.white
        dataTable.delegate = self as? UICollectionViewDelegate
        dataTable.dataSource = self

        if let layout = dataTable.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }



        webView = WKWebView()
        webView.navigationDelegate = self
        //view = webView



        let url = URL(string: "https://someWebsite.com")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true



        runData()

    }





    ///////ADDS DELAY
    func runData() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 4) { // Change `2.0` to the desired number of seconds.

            self.setWebViewValue(name: "txtValue", data: self.submittedValue2, vin: self.currentSelection2)

        }
    }






    ///////// PULLS DATA
    func setWebViewValue(name: String, data: String, vin: String) {


        if vin == "VIN:" {

            webView.evaluateJavaScript("document.getElementById('rbRequest_1').click()", completionHandler: nil)
        }
        else {
        }

        webView.evaluateJavaScript("document.getElementById(\"\(name)\").value = \"\(data)\"", completionHandler: nil)

        webView.evaluateJavaScript("document.getElementById('btnSubmit').click()", completionHandler: nil)

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { // Change `2.0` to the desired number of seconds.

            self.webView.evaluateJavaScript("document.documentElement.outerHTML.toString()") { (result, error) -> Void in
            if error != nil {
                print(error!)
            }
                let document = try! SwiftSoup.parse(result as! String)

                for row in try! document.select("table[id=\"gvTests\"] tr") {
                    var rowContent = [String]()

                    for col in try! row.select("td") {
                        let colContent = try! col.text()
                        rowContent.append(colContent)
                    }
                    self.tableContent.append(rowContent)
                }
                if self.tableContent.isEmpty == false {
                    //self.tableContent.remove(at: 0)
                    self.tableContent[0] = ["Make","Model","Year","Date","Pass/Fail","Certificate","Referee"]
                }
                print(self.tableContent)
                self.tableContent = self.transpose(input: self.tableContent)
                if self.tableContent.isEmpty == false {
                    self.dataTable.reloadData()
                }
            }
            self.dismiss(animated: false, completion: nil)
        }
    }



    ////// Collection View functions
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        if tableContent.isEmpty == false {
            return tableContent[0].count
        }
        else {
            return 0
        }
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if tableContent.isEmpty == false {
            return tableContent.count
        }
        else {
            return 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)


        let title = UILabel(frame: CGRect(x: 0,y:  0,width: cell.bounds.size.width,height: cell.bounds.size.height))



        for subview in cell.contentView.subviews {

            subview.removeFromSuperview()

        }

        cell.contentView.addSubview(title)


        title.text = tableContent[indexPath.section][indexPath.item]
        //title.textColor = UIColor.black

        title.layer.borderWidth = 1
        title.layer.borderColor = UIColor.black.cgColor
        title.textAlignment = NSTextAlignment.center


        return cell
    }


    public func transpose<T>(input: [[T]]) -> [[T]] {
        if input.isEmpty { return [[T]]() }
        let count = input[0].count
        var out = [[T]](repeating: [T](), count: count)
        for outer in input {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }

        return out
    }



    func dismissVC() {
        dismiss(animated: true, completion: nil)
    }



}
Tecra
  • 13
  • 5
  • `dataTable.delegate = self as? UICollectionViewDelegate` ?? – SPatel Mar 22 '19 at 04:24
  • I removed that line, same issue nothing changed – Tecra Mar 22 '19 at 04:39
  • Don't remove entire line, just keep `dataTable.delegate = self` – SPatel Mar 22 '19 at 04:41
  • Then I get the error message "Cannot assign value of type 'SecondViewController' to type 'UICollectionViewDelegate?'" – Tecra Mar 22 '19 at 04:42
  • _Not related_ but you shouldn't add `IBAction` next to `IBOutlet` and then _variables_ after that . You should add `IBAction` methods generally after ViewController life cycle methods . – Shubham Bakshi Mar 22 '19 at 05:05
  • @Tecra that mean your view controller does not conform to that protocol, so you need to conform that line datasource – SPatel Mar 22 '19 at 05:15
  • @SPatel I added the UICollectionViewDelegate to the class and the error went away, but the original issue is still there, nothing changed – Tecra Mar 22 '19 at 05:22
  • @ShubhamBakshi So I should have it as IBOutlet ---> Variables ----> ViewDidLoad() ----> IBAction ? – Tecra Mar 22 '19 at 05:24
  • Yeah ! That's the common pattern we use while programming :P – Shubham Bakshi Mar 22 '19 at 05:49
  • @CodeDifferent I used the code you posted in this question : https://stackoverflow.com/questions/47487040/how-to-parse-html-table-data-to-array-of-string-in-swift , so the "for row in try! document.select("table[id=\"gvTests\"] tr")" works in the simulator, but is results empty on the actual device, do you have any idea why? Would really appreciate the help. – Tecra Mar 22 '19 at 06:47

2 Answers2

0

This might cause from constraint on your collectionView.

0

Turns out the issue is not with the UIcollectionview, but that the data is empty because instead of being extracted from the website like it is when ran in the simulator. I will post another question for that. Thanks all.

Tecra
  • 13
  • 5