0

вот мой код он все парсит все работает но он почему то создает слишком много копий

        class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

            @IBOutlet weak var NameLabel: UILabel!
            @IBOutlet weak var LogoPicture: UIImageView!

            let zoomImageView = UIView()
            let urlString = "sdfsdf"

            @IBOutlet weak var tableView: UITableView!

            var nameArray = [String]()
            var timeArray = [NSNumber]()
            var logoArray = [String]()
            var bodyArray = [String]()
            var img1Array = [String]()
            var img2Array = [String]()
            var img3Array = [String]()
            var titleArray = [String]()


            override func viewDidLoad() {
                super.viewDidLoad()



            /*zoomImageView.frame = CGRect (x: 32, y: 0, width: 200, height: 100)
            zoomImageView.backgroundColor = UIColor.red
            zoomImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "animate"))
            view.addSubview(zoomImageView)*/




            let defaults = UserDefaults.standard
            if let name = defaults.string(forKey: "NameText"){
            NameLabel.text = name
            }
            if let logo = defaults.string(forKey: "LogoText"){
                let strurl = NSURL(string: logo)
                if let dtinternet = NSData(contentsOf:strurl! as URL) {
                    LogoPicture.image = UIImage(data: dtinternet as Data) }
                self.view.addSubview(LogoPicture)
                LogoPicture.layer.borderWidth = 1
                LogoPicture.layer.masksToBounds = false
                LogoPicture.layer.borderColor = UIColor.clear.cgColor
                LogoPicture.layer.cornerRadius = LogoPicture.frame.height/2
                LogoPicture.clipsToBounds = true}

            self.downloadJsonWithURL()


        }

        @IBAction func ExitButton(_ sender: Any) {

            UserDefaults.standard.set(false, forKey: "isUserLoggedIn");
            UserDefaults.standard.synchronize();
        }

        func downloadJsonWithURL(){
            let url = NSURL(string: urlString)
            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in

                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                    as? NSDictionary {
                    //print(jsonObj!.value(forKey: "data"))

                    if let dataArray = jsonObj!.value(forKey: "data") as? NSArray {
                        for datata in dataArray {
                            if let dataDict = datata as?  NSDictionary {

                                if let title = dataDict.value(forKey: "title") {
                                    self.titleArray.append(title as! String)
                                }

                                if let created = dataDict.value(forKey: "created") {
                                    created as! Double
                                    let date = NSDate(timeIntervalSince1970: TimeInterval(created as! NSNumber))
                                    let dateFormatter = DateFormatter()
                                    dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
                                    dateFormatter.locale = NSLocale.current
                                    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                                    self.timeArray.append(dateFormatter.string(from: date as Date))
                                }
                                if let body = dataDict.value(forKey: "body") {
                                    self.bodyArray.append(body as! String)
                                }
                                if let img1 = dataDict.value(forKey: "image1") {
                                    self.img1Array.append(img1 as! String)
                                }
                                else { self.img1Array.append(" nil " as! String)}

                                if let img2 = dataDict.value(forKey: "image2") {
                                    self.img2Array.append(img2 as! String)
                                }
                                else { self.img2Array.append(" nil " as! String)}

                                if let img3 = dataDict.value(forKey: "image3") {
                                    self.img3Array.append(img3 as! String)
                                }
                                else { self.img3Array.append(" nil " as! String)}

                                if let authorArray = dataArray.value(forKey: "author") as? NSArray {
                                    for datata1 in authorArray {
                                        if let authorDict = datata1 as?  NSDictionary {
                                            if let namea = authorDict.value(forKey: "name") {
                                                 self.nameArray.append(namea as! String)
                                            }
                                            if let logo = authorDict.value(forKey: "logo") {
                                                self.logoArray.append(logo as! String)
                                            }
                                        }
                                    }
                                }


                                OperationQueue.main.addOperation({ self.tableView.reloadData()})
                            }
                            //return
                        }
                    }
                    //print(self.timeArray)

                }

            }).resume()

        }



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


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell.nameLable.text = "\(nameArray[indexPath.row])"
        cell.likeLabel.text = bodyArray[indexPath.row]
        //print(nameArray[indexPath.row])
        cell.dataLabel.text = timeArray[indexPath.row]

        /*let imgURL = NSURL(string: logoArray[indexPath.row])
        if imgURL != nil {
        let data = NSData(contentsOf: imgURL! as URL)
        cell.logoImg.image = UIImage(data: data! as Data)
        }*/
        let imageView = cell.logoImg!
        imageView.sd_setImage(with: URL(string: logoArray[indexPath.row]))

        let imgURL3 = NSURL(string: img3Array[indexPath.row])
        let imgURL2 = NSURL(string: img2Array[indexPath.row])
        let imgURL1 = NSURL(string: img1Array[indexPath.row])
        cell.img1.frame = CGRect(x: 13, y: 5, width: 300, height: 145)
        cell.img1.isUserInteractionEnabled = true
        //cell.img1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "animate"))

        //cell.img2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "animate"))
        //cell.img3.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "animate"))




        if imgURL3 == nil {
            cell.img3.image = nil
            if imgURL2 == nil {
                cell.img2.image = nil
                if imgURL1 == nil {
                    cell.img1.image = nil
                }
                else {
                    cell.img1.frame = CGRect(x: 13, y: 5, width: 300, height: 145)
                    let imageView1 = cell.img1!
                    imageView1.sd_setImage(with: URL(string: img1Array[indexPath.row]))
                }

            }
            else {
                cell.img1.frame = CGRect(x: 13, y: 5, width: 147, height: 145)
                cell.img2.frame = CGRect(x: 166, y: 5, width: 147, height: 145)
                let imageView1 = cell.img1!
                imageView1.sd_setImage(with: URL(string: img1Array[indexPath.row]))
                let imageView2 = cell.img2!
                imageView2.sd_setImage(with: URL(string: img2Array[indexPath.row]))
            }

        }
        else {
            cell.img1.frame = CGRect(x: 13, y: 5, width: 147, height: 145)
            cell.img2.frame = CGRect(x: 166, y: 5, width: 144, height: 71)
            cell.img3.frame = CGRect(x: 166, y: 79, width: 144, height: 71)

            let imageView1 = cell.img1!
            imageView1.sd_setImage(with: URL(string: img1Array[indexPath.row]))
            let imageView2 = cell.img2!
            imageView2.sd_setImage(with: URL(string: img2Array[indexPath.row]))
            let imageView3 = cell.img3!
            imageView3.sd_setImage(with: URL(string: img3Array[indexPath.row]))

        }
        print(timeArray)
        return cell


    }
    func animate() {
        UIView.animate(withDuration: 0.75) {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
            let height = (cell.frame.width/200) * 100
            let y = cell.frame.height / 2 - height / 2
            cell.img1.frame = CGRect(x: 0, y: y, width: self.view.frame.width , height: height)
        }

    }




}

вот что он выдает через print(timeArray)

[1497856315, 1497688102, 1497614594, 1497337111, 1493924259, 1492888300, 1492194473, 1492099489, 1491910949, 1491725464, 1491467821, 1491228362, 1490703933, 1490360502, 1490277769, 1490102294, 1489492056, 1489146214, 1488996898, 1487836270, 1487679238, 1487608135, 1486135833, 1486135831, 1485499621, 1483602378, 1480939014, 1480930692, 1480772053, 1478714056, 1475063435, 1474374128, 1471287515, 1471286235, 1470754384, 1469621456, 1469102821, 1469002404, 1468420343, 1468419387, 1468419242, 1468418750, 1468417262, 1468414617, 1468329183, 1468221936, 1467969766, 1467806108, 1467805914, 1467805781, 1467805474, 1467788577, 1467706157, 1467630892, 1467628966, 1467451711, 1467226414, 1467180754]
[1497856315, 1497688102, 1497614594, 1497337111, 1493924259, 1492888300, 1492194473, 1492099489, 1491910949, 1491725464, 1491467821, 1491228362, 1490703933, 1490360502, 1490277769, 1490102294, 1489492056, 1489146214, 1488996898, 1487836270, 1487679238, 1487608135, 1486135833, 1486135831, 1485499621, 1483602378, 1480939014, 1480930692, 1480772053, 1478714056, 1475063435, 1474374128, 1471287515, 1471286235, 1470754384, 1469621456, 1469102821, 1469002404, 1468420343, 1468419387, 1468419242, 1468418750, 1468417262, 1468414617, 1468329183, 1468221936, 1467969766, 1467806108, 1467805914, 1467805781, 1467805474, 1467788577, 1467706157, 1467630892, 1467628966, 1467451711, 1467226414, 1467180754]

здесь 2 раза одно и тоже зачем он это делает и он продолжает дальше через пару минут было бы еще + 2 и т.д.

возможно дело не в парсе? а в помещении данных в cell

2 ответа 2

1

Вы выводите данные

print(timeArray)

в cellForRowAt. Проблема у Вас здесь в том, что ячейки в UITableView переиспользуемые, поэтому когда скроллите, постоянно вызывается этот метод и выполняется все что Вы там прописали.

Будет что-то тяжелое, что долго будет отрабатывать - получите дикие подтормаживания.

Всю подготовительную работу для обработки данных, которые будете кормить в tableView вынесите внутрь Вашей URLSession.shared.dataTask.... Т.е. что Вы делаете в ячейке:

let date = NSDate(timeIntervalSince1970: TimeInterval(timeArray[indexPath.row]))
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
cell.dataLabel.text = dateFormatter.string(from: date as Date)

Изначально пройдитесь и сложите в массив в уже готовом виде, а в ячейке только отдавайте готовую строку:

cell.dataLabel.text = formattedTimeStringArray[indexPath.row]

И т.д.

Так что главное - ячейки в UITableView переиспользуемые.

5
  • спасибо большое, дату я перенес, но программа все так же тормозит и в принципе ничего не изменилось((((
    – Sergey
    26 июн 2017 в 11:45
  • почему он при скролле постоянно запрашивает array почему ему недостаточно одного раза как в другом любом языке програмированния, сори за глупые вопросы просто я недавно начал использовать Swift и многое бывает непонятно @VAndrJ
    – Sergey
    26 июн 2017 в 11:54
  • @Sergey не только дату нужно выносить. Вот смотрю картинки грузятся в ячейках. Так тоже нельзя делать, необходимо это делать в отдельном потоке и т.д., пока об этом не будем. Наиболее простое решение для Вас - использовать библиотеку для асинхронной загрузки картинок, вот хороший вариант: github.com/rs/SDWebImage .
    – VAndrJ
    26 июн 2017 в 13:11
  • спасибо большое вы мне очень помогли буду очень признателен если еще что подскажите по моему коду
    – Sergey
    26 июн 2017 в 16:42
  • пожалуйста загляните вот сюда тоже . (ru.stackoverflow.com/questions/682482/…) . ну и вот сюда еще раз пожалуйста . (ru.stackoverflow.com/questions/683630/…)
    – Sergey
    26 июн 2017 в 16:43
0

Нужно просто вынести все из ячеек в метод где забираются данные, так как это не по времени получается такое, судя по коду, а при скролле.

2
  • под все вы имеете 'if ' тоже? тогда как проверять на ошибки
    – Sergey
    26 июн 2017 в 11:51
  • почему он при скролле постоянно запрашивает array почему ему недостаточно одного раза как в другом любом языке программирования, сори за глупые вопросы просто я недавно начал использовать Swift и многое бывает непонятно @Son'ka V
    – Sergey
    26 июн 2017 в 11:55

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.