Swift 将图像链接到集合视图中

Swift 将图像链接到集合视图中,swift,uicollectionview,swift3,Swift,Uicollectionview,Swift3,我正在尝试从url获取图像到我的集合视图中。可以显示的图像数量取决于阵列计数 这是我的密码: class CollectionViewController: UICollectionViewController { @IBOutlet weak var searchBox: UITextField! var imageArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() } let

我正在尝试从url获取图像到我的集合视图中。可以显示的图像数量取决于阵列计数

这是我的密码:

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
}

class CollectionViewController:UICollectionViewController{
@IBVAR搜索框:UITextField!
var imageArray:[字符串]=[]
重写func viewDidLoad(){
super.viewDidLoad()
}
让链接=”https://www.googleapis.com/my_link_is_here"        
guard let url=url(字符串:链接)else{
打印(“错误:无法创建URL”)
返回
}
let request=URLRequest(url:url)
URLSession.shared.dataTask(with:request){data,response,中的错误
保护错误==nil else{
打印(“调用GET on/todos/1时出错”)
打印(错误!)
返回
}
做{
guard let json=try JSONSerialization.jsonObject(with:data!,options:[])作为?[String:Any]其他{
打印(“\(错误?.localizedDescription)”)
返回
}
//打印(“待办事项是:”+json.description)
guard let todotitle=json[“items”]作为?[Any]其他{
打印(“无法从JSON获取todo标题”)
返回
}
让arrcnt=todotitle.count
变量i=0
而(iInt{
//#警告未完成执行,返回节数
返回1
}
重写func collectionView(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int{
//#警告未完成执行,返回项目数
返回self.imageArray.count
}

问题是当我写“return self.imageArray.count”时,它返回nil。它采用空数组的数组的初始化值。如何计算附加后的最终数组。

在执行
while
循环后,需要在主线程上重新加载
集合视图。您还可以通过使用单个
guard
语句而不是多个语句来减少代码,并使用for循环而不是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()
    }
}

可以显示imageArray的声明吗?类CollectionViewController:UICollectionViewController{@IBOutlet弱变量搜索框:UITextField!var imageArray:[字符串]=[]重写func viewDidLoad(){super.viewDidLoad()永远不要在评论中添加你的代码,而不要编辑你的问题。这已经完成了。你有任何错误吗?只有通过重新加载集合视图?@GauravKapur Welcome mate:)@GauravKapur Hey请现在接受答案,然后它对你有效。