This code pulls JSON from a server and delivers some data like imageURL
, titleString
and videoURL
. Then it places them in a UICollectionView
and displays them.
import UIKit
import Alamofire
class vcWatch: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var myCollectionView: UICollectionView!
var images:[String] = []
var videos:[String] = []
var lableTitles:[String] = []
let link = "http://alifetouched.com/lib/videos.json.php"
override func viewDidLoad() {
super.viewDidLoad()
myActivityIndicator.isHidden = false
myActivityIndicator.startAnimating()
loadImages()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:cvCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! cvCell
// Videos
let requestURL = URL(string:self.videos[indexPath.row])
let request = URLRequest(url: requestURL!)
// Images
let imageString = self.images[indexPath.row]
let imageUrl = NSURL(string: imageString)
let imageData = NSData(contentsOf: imageUrl! as URL)
cell.videoCell.loadRequest(request)
cell.labelCell.text = self.lableTitles[indexPath.row]
if(imageData != nil){
cell.imageCell.image = UIImage(data: imageData! as Data)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath){
print("User Tapped: \(indexPath.row)")
}
func loadImages() {
Alamofire.request(link)
.validate()
.responseJSON { (response) in
guard response.result.isSuccess else {
print("Error with response: \(response.result.error)")
return
}
guard let dict = response.result.value as? Dictionary <String,AnyObject> else {
print("Error with dictionary: \(response.result.error)")
return
}
guard let dictData = dict["VideoJSON"] as? [Dictionary <String,AnyObject>] else {
print("Error with dictionary data: \(response.result.error)")
return
}
for data in dictData {
self.videos.append(data["media_url"] as! String)
self.images.append(data["icon_url"] as! String)
self.lableTitles.append(data["title"] as! String)
}
self.myCollectionView.reloadData()
self.myActivityIndicator.stopAnimating()
self.myActivityIndicator.isHidden = true
return
}
}