I was trying to make a wallpaper app and my code was working all fine when I had the entire implementation in the ViewController file. And then I shifted some of the code to another class. Here is the code.
ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
photoOperations.getStuffFromJson()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoOperations.previewUrlArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
if let img = self.images[indexPath] {
cell.imageView.image = img
} else {
photoOperations.downloadThumbnail(indexPath.row){ (image) in
dispatch_async(dispatch_get_main_queue()) {
if let img = image {
cell.imageView.image = img
self.images[indexPath] = img
} else {
print("Images will be loaded in a few seconds!")
}
}
}
}
return cell
}
PhotoOperations.swift
func getStuffFromJson( ){
Alamofire.request(.GET, "https://example.com/api/", parameters: ["key": "123.."])
.responseJSON{ response in
if let value = response.result.value {
let hits = JSON(value)["hits"]
var counter = 0
while counter < hits.count {
if let previewString = hits[counter]["previewURL"].rawString(){
self.previewURL = NSURL(string: previewString)!
self.previewUrlArray.append(self.previewURL!)
counter += 1
} else{ print("Error : A previewURL wasn't found.")
}}}}}
func downloadThumbnail(forIndexPathAtRow : Int , completion: (UIImage?)->Void) {
if previewUrlArray.count > 0 {
... // create URL task , session etc.
}
}
How do I reload the data in the ViewController? I tried adding a collectionView parameter to the getStuffFromJSON
method and calling collectionView.reload at the end. But that doesn't work. Also I get 0 as previewURLArray.count
in the numberOfItemsInSection
method.