Изображение, переданное из API, не отображается в контейнере просмотра страниц Swift - PullRequest
0 голосов
/ 28 мая 2018

Я работаю над приложением для iOS, которое взаимодействует с API, используя alamofire и swiftyJSON.В этом API я возвращаю кучу значений, и одно из них - изображения.Возвращенные изображения поступают в виде массива, но я могу перебирать массив и отображать одно изображение.Чтобы сделать приложение более продвинутым, я решил внедрить в свое приложение класс UIPageViewController .Я вызвал функцию API и попытался передать свои изображения в контроллеры представления.

Список вещей в моей раскадровке

  1. A UIPageView
  2. UiViewController с встроенным в него UIImage.

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

protocol ProductImagesPageViewControllerDelegate: class {
    func setupPageController(numberOfPages: Int)
    func turnPageController(to index: Int)
}

class ProductPageVC: UIPageViewController {

    weak var  pageViewControllerDelegate: ProductImagesPageViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        automaticallyAdjustsScrollViewInsets = false
        dataSource = self
        delegate = self

    }


    func configureImg() {
        let productId = ProductServices.instance.selectedProduct?.id
        ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

            if success {
                ProductServices.instance.productDetails.forEach({ (productDetail) in

                    let images = productDetail.productImg.count

                    if images > 0 {

                        for image in 0..<(images) {

                            let imageVC = self.storyboard?.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                            self.controllers.append(imageVC!)

                        }
                    }

                })
            }
        })
    }

    lazy var controllers: [UIViewController] = {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        var controllers = [UIViewController]()


        let productId = ProductServices.instance.selectedProduct?.id
        ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

            if success {
                ProductServices.instance.productDetails.forEach({ (productDetail) in

                    let images = productDetail.productImg.count

                    if images > 0 {

                        for image in 0..<(images) {

                            let imageVC = storyboard.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                            controllers.append(imageVC)

                        }
                    }

                })
            }
        })



        self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)

        return controllers
    }()



    func turnToPage(index: Int)
    {
        let controller = controllers[index]
        var direction = UIPageViewControllerNavigationDirection.forward

        if let currentVC = viewControllers?.first {
            let currentIndex = controllers.index(of: currentVC)!
            if currentIndex > index {
                direction = .reverse
            }
        }

        self.configureDisplaying(viewController: controller)

        setViewControllers([controller], direction: direction, animated: true, completion: nil)
    }

    func configureDisplaying(viewController: UIViewController)
    {
        for (index, vc) in controllers.enumerated() {
            if viewController === vc {
                if let imageVC = viewController as? ImagesVC {

                    imageVC.configureImage(productIndex: index)

                    self.pageViewControllerDelegate?.turnPageController(to: index)
                }
            }
        }
    }
}
// MARK: - UIPageViewControllerDataSource

extension ProductPageVC : UIPageViewControllerDataSource
{
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        if let index = controllers.index(of: viewController) {
            if index > 0 {
                return controllers[index-1]
            }
        }

        return controllers.last
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {

        if let index = controllers.index(of: viewController) {
            if index < controllers.count - 1 {
                return controllers[index + 1]
            }
        }

        return controllers.first
    }
}

extension ProductPageVC : UIPageViewControllerDelegate {

    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController])
    {
        self.configureDisplaying(viewController: pendingViewControllers.first as! ImagesVC)
    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if !completed {
            self.configureDisplaying(viewController: previousViewControllers.first as! ImagesVC)
        }
    }
}

Это мой код ImageVC

class ImagesVC: UIViewController {

    @IBOutlet weak var imageView: UIImageView!


    func configureImage(productIndex : Int) -> Void {

        ProductServices.instance.productDetails.forEach { (productImg) in

            if productImg.productImg.count > 0 {
                imageView.sd_setImage(with: URL(string: productImg.productImg[productIndex]!) )
            } else {
                imageView.image = UIImage(named: "image_not_found")
            }
        }

    }}

Это мой код HeaderImageView

class HeaderImageVC: UIView {

    @IBOutlet weak var pageControl: UIPageControl!
}

extension HeaderImageVC : ProductImagesPageViewControllerDelegate {
    func setupPageController(numberOfPages: Int)
    {
        pageControl.numberOfPages = numberOfPages
    }

    func turnPageController(to index: Int)
    {
        pageControl.currentPage = index
    }
}

Понятия не имею, почему кодне работает, но дополнительные коды будут предоставлены по запросу.Спасибо.

В соответствии с предложением

var images = (ProductServices.instance.productDetails.first?.productImg) 

    lazy var controllers: [UIViewController] = {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        var controllers = [UIViewController]()

        if let images = self.images {
            for image in images {
                let imageVC = storyboard.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                controllers.append(imageVC)
            }
        }



        self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)

        return controllers
    }()

все равно возвращается пустое

1 Ответ

0 голосов
/ 31 мая 2018

проблема

lazy var controllers: [UIViewController] = {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var controllers = [UIViewController]()

    // IT WILL NOT WAIT TO FINISH IT
    let productId = ProductServices.instance.selectedProduct?.id
    ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

        if success {
            ProductServices.instance.productDetails.forEach({ (productDetail) in

               // NO USE OF productDetail as it is already returned 

                let images = productDetail.productImg.count

                if images > 0 {

                    for image in 0..<(images) {

                        let imageVC = storyboard.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                        controllers.append(imageVC)

                    }
                }

            })
        }
    })


    // controllers.count is 0

    self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)

    return controllers
}()

если вы соблюдаете приведенный выше код и должны отладить его, то вы обнаружите, что controllers пусто, поскольку это асинхронная задача, и компилятор не будет ждатьдля завершения findIndividualProducts задание для его завершения вернет пустой массив, который вы определили, поэтому в результате вашему контроллеру нечего показывать !!-> Имеет смысл

Решение заключается в том, что вы можете просто создать метод, который будет устанавливать вызов API findIndividualProducts и назначать его controllers, теперь контроллер является простым простым свойством.

Надеюсь, что это полезно

РЕДАКТИРОВАТЬ

Сначала создайте один метод и вызывайте его из вида, когда загрузка или просмотр будут отображаться так, как вам удобно

 private func getAllControllers () {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var controllers = [UIViewController]()

    // IT WILL NOT WAIT TO FINISH IT
    let productId = ProductServices.instance.selectedProduct?.id
    ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

        if success {
            ProductServices.instance.productDetails.forEach({ (productDetail) in

               // NO USE OF productDetail as it is already returned 

                let images = productDetail.productImg.count

                if images > 0 {

                    for image in 0..<(images) {

                        let imageVC = storyboard.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                        controllers.append(imageVC)

                    }


  self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)
  self.controllers = controllers
                }

            })
        }
    })

}

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

var controllers: [UIViewController] = []

...