2016-12-29 2 views
0

Я пытаюсь получить изображения из URL-адреса в мой коллекционный вид. количество отображаемых изображений зависит от количества массивов.Url images in collection Просмотреть

Вот мой код:

class CollectionViewController: UICollectionViewController { 


@IBOutlet weak var searchBox: UITextField! 


var imageArray:[String] = [] 


override func viewDidLoad() { 
    super.viewDidLoad() 
} 

    let link = "https://www.googleapis.com/my_link_is_here"   
    guard let url = URL(string: link) else { 

     print("Error: cannot create URL") 
     return 

    } 

    let request = URLRequest(url: url) 

    URLSession.shared.dataTask(with: request) { data, response, error in 

     guard error == nil else { 

      print("error calling GET on /todos/1") 
      print(error!) 
      return 
     } 

     do{ 

      guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any] else { 

       print("\(error?.localizedDescription)") 
       return 
      } 

      //print("The todo is: " + json.description)             
      guard let todotitle = json["items"] as? [Any] else { 
       print("Could not get todo title from JSON") 
       return 
      } 

      let arrcnt = todotitle.count 


      var i = 0 

      while (i < arrcnt){ 

       guard let todotitle1 = todotitle[i] as? [String: Any] else { 
        print("Could not get todo title1 from JSON") 
        return 
       } 


       guard let todotitle2 = todotitle1["image"] as? [String : Any] else { 
        print("Could not get todo title2 from JSON") 
        return 
       } 

       guard let todotitle3 = todotitle2["thumbnailLink"] as? String else { 

       // continue 
       print("Could not get todo title3 from JSON") 
       return 

       } 

       self.imageArray.append(todotitle3) 

       print(self.imageArray) 

       i += 1 

      }             
     }catch{ 
      print("error trying to convert data to JSON") 
      return 
     } 

     }.resume() 

} 



/* 
// MARK: - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

// MARK: UICollectionViewDataSource 

override func numberOfSections(in collectionView: UICollectionView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    // #warning Incomplete implementation, return the number of items 
    return self.imageArray.count 
} 

Проблема заключается в том, когда я пишу «обратный self.imageArray.count» возвращает ноль. Требуется инициализированное значение массива, который является пустым массивом. Как подсчитать окончательный массив после его добавления.

+0

Можете ли вы показать объявление imageArray? –

+0

класс CollectionViewController: UICollectionViewController { @IBOutlet слабый поиск varBox: UITextField! вар imageArray: [String] = [] переопределения функа viewDidLoad() { super.viewDidLoad() – Gaurav

+0

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

ответ

0

Вам необходимо перезагрузить collectionView в основной теме после вашего цикла while. Кроме того, вы можете уменьшить свой код, сделав вместо него один оператор guard вместо использования и вместо него использовать цикл while, поэтому весь код будет таким.

do{ 

    guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any] else { 

     print("\(error?.localizedDescription)") 
     return 
    } 

    //print("The todo is: " + json.description) 
    guard let array = json["items"] as? [[String : Any]] else { 
     print("Could not get todo title from JSON") 
     return 
    } 
    for dic in array { 
     guard let imageDic = dic["image"] as? [String : Any], let thumbnailLink = imageDic["thumbnailLink"] as? String else { 
      print("Could not get thumbnailLink") 
      return 
     } 
     self.imageArray.append(thumbnailLink) 
    } 
    //Now you need to reload the collectionView on main thread. 
    DispatchQueue.main.async { 
     self.collectionView.reloadData() 
    } 
} 
+0

только путем перезагрузки коллекции? – Gaurav

+0

@GauravKapur Проверьте отредактированный ответ :) –

+0

Это сработало .. так сильно! – Gaurav