我已经搞混了这么长时间了,我无法弄清楚如何将URL加载到我拥有的UICollectionView中。 我能够仅打印该图像中显示的URL。
这是我用来访问API的游乐场代码。
let fortniteChallengesURL9 = URL(string: "https://api.fortnitetracker.com/v1/store")
if let unwrappedURL = fortniteChallengesURL9 {
var request = URLRequest(url: unwrappedURL) request.addValue("MY API KEY", forHTTPHeaderField: "TRN-Api-Key")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, err) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
print((json as AnyObject).value(forKey: "imageUrl")!)
// print((json as AnyObject).value(forKey: "name")!)
let urlImages = (json as AnyObject).value(forKey: "imageUrl")!
DispatchQueue.main.asyncAfter(deadline: .now() ) {
}
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}
}
dataTask.resume()
}
然后是我要放入的UICollectionView。但是,我弄乱了这段代码,试图弄清楚该怎么做。我认为,当前集合中的图像必须替换为WebViews。
var arrayOfImages = [UIImage]()
var arrayOfIds = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)
collectionViewLayout?.invalidateLayout()
arrayOfImages = [#imageLiteral(resourceName: "Sats"),#imageLiteral(resourceName: "location"),#imageLiteral(resourceName: "news"),#imageLiteral(resourceName: "challengeBtn"),#imageLiteral(resourceName: "LTM")]
arrayOfIds = ["A","B","C","D","E"]
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayOfImages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as UICollectionViewCell
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = arrayOfImages[indexPath.row]
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let name = arrayOfIds[indexPath.row]
let viewController = storyboard?.instantiateViewController(withIdentifier: name)
self.navigationController?.pushViewController(viewController!, animated: true)
}
如果任何人都可以找到有关如何执行此操作的完整教程的链接,那将很棒。如果不是,请提供帮助,因为我不知道从何处开始使用collectionView,并且我只想使用swift而不使用任何第三方变通办法。另外,我会用我认为还是只保留imageViews的webView替换图像视图。
答案 0 :(得分:0)
您可以尝试
struct Root:Decodable {
let imageUrl:String
}
var arrayOfImages = [Root]()
arrayOfImages = try? JSONDecoder().decode([Root].self,from:data)
然后在cellForRowAt
内使用SDWebImage
imageView.sd_setImage(with: URL(string:arrayOfImages[indexPath.row].imageUrl), placeholderImage: UIImage(named: "placeholder.png"))
不要在回调内重新加载集合
DispatchQueue.main.async {
self.collectionView.reloadData()
}