我想從url中獲取圖像到我的集合視圖中。可以顯示的圖像數量取決於陣列數量。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
}
問題是,當我寫 「返回self.imageArray.count」 則返回nil。它將數組的初始化值作爲一個空數組。附加後如何計算最終數組。
你可以顯示imageArray的聲明嗎? –
class CollectionViewController:UICollectionViewController { @IBOutlet weak var searchBox:UITextField! VAR imageArray:[字符串] = [] 覆蓋FUNC viewDidLoad中(){ super.viewDidLoad() – Gaurav
絕不添加你的代碼註釋中,而不是編輯你的問題。 –