I want to download images from server and display in UICollectionView. First time when user connect with internet than all images will download in background and display from local directory when user is offline. I am using alamofire to download the images. Firstly i am checking existence of image, if it is not already dowloaded than i download it. The problem is that the album is not showing when it is already downloaded. I do not know how. Here is my code:
import UIKit
import Alamofire
var myurl : URL!
var imageName : String!
var bool = false
let docsurl = try! FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (background_imageurl.count > 0) {
if Reachability.isConnectedToNetwork() == true{
downloadAllImages(urlArray : background_imageurl)
}
}
}
func downloadAllImages(urlArray:[String])->Void{
for i in 0 ..< urlArray.count {
let fullName = urlArray[i]
let fullNameArr = (fullName as AnyObject).components(separatedBy: "//")
let imgname = fullNameArr[1]
let tempimgname = imgname
let tempimgname2 = tempimgname.components(separatedBy: "/")
imageName = tempimgname2[4]
myurl = docsurl.appendingPathComponent("\("guidedCellImages")/\(self.imageName!)")
print("\n myurl", myurl)
if FileManager.default.fileExists(atPath: myurl.path, isDirectory: &bool),bool.boolValue {
print("\n fileExists", myurl.path)
}else{
downloadFile(url: urlArray[i] as! String)
}
}
}
func downloadFile(url: String)->Void{
let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
(temporaryURL, response) in
let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filePath = directoryURL?.appendingPathComponent("\("guidedCellImages")/\(self.imageName!)")
return (filePath!, [.removePreviousFile, .createIntermediateDirectories])
}
let utilityQueue = DispatchQueue.global(qos: .utility)
print("url", url)
Alamofire.download(
url,
method: .get,
encoding: JSONEncoding.default,
to: destination)
.downloadProgress(queue: utilityQueue) { progress in
}
.response(completionHandler: { (DefaultDownloadResponse) in
if (self.urlArray.count > 0){
self.urlArray.removeFirst()
print("self.urlArray", self.urlArray.count)
}
if DefaultDownloadResponse.response?.statusCode == 200 {
print(DefaultDownloadResponse.destinationURL!)
}
})
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
myurl = docsurl.appendingPathComponent("\("guidedCellImages")")
if FileManager.default.fileExists(atPath: myurl.path, isDirectory: &bool),bool.boolValue {
let directoryContents = try! fileManager.contentsOfDirectory(at: myurl, includingPropertiesForKeys: nil)
print("\ndirectoryContents", directoryContents)
for imageURL in directoryContents where imageURL.pathExtension == "png" {
if let image = UIImage(contentsOfFile: imageURL.path) {
cell.tab1GuidedimageView.image = image
} else {
fatalError("Can't create image from file \(imageURL)")
}
}
}else{
if (background_imageurl.count > 0 ){
cell.tab1imageView.sd_setImage(with: URL(string: background_imageurl[indexPath.row]), placeholderImage: UIImage(named: "background"),options: .refreshCached)
}
}
return cell
}