WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Project 12: Challenge 1 - Save how many times shows image.

Forums > 100 Days of Swift

Hello, I try to approach to challenge 1. I make whole code, where it seems be good, but It's not working, and i don't know why. Anyone can help me with this?

import UIKit

class ViewController: UITableViewController {

    class Model: Codable {
        let picture: String
        var count = 0

        init(picture: String) {
            self.picture = picture
        }
    }

    var pictures = [Model]() {
        didSet {
            tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Image Viewer"
        navigationController?.navigationBar.prefersLargeTitles = true

       performSelector(inBackground: #selector(fetchData), with: nil)

        tableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: false)
        save()
        pictures = pictures.sorted(by: { $0.picture < $1.picture })

       let defaults = UserDefaults.standard
        if let savedCounter = defaults.object(forKey: "count") as? Data {
            let jsonDecoder = JSONDecoder()

            do {
                pictures = try jsonDecoder.decode([Model].self, from: savedCounter)
            } catch {
                print("Failed to load counter")
            }
        }
    }

    func save() {
        let jsonEncoder = JSONEncoder()
        if let savedData = try? jsonEncoder.encode(pictures.count) {
            let defaults = UserDefaults.standard
            defaults.set(savedData, forKey: "count")
        } else {
            print("Failed to save counter.")
        }
    }

    @objc func fetchData() {
        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)

        DispatchQueue.main.async { [weak self] in
            for item in items {
                if item.hasPrefix("nssl") {
                    self?.pictures.append(Model(picture: item))
                }
            }
        }
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return pictures.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
        let model = self.pictures[indexPath.row]
        cell.textLabel?.text = model.picture
        cell.detailTextLabel?.text = "Performed to image times: \(model.count)"
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let vc = storyboard?.instantiateViewController(identifier: "Detail") as? DetailViewController {
            let model = pictures[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
            vc.detailVCTitle = "Picture \(indexPath.row + 1) of \(pictures.count)"
            vc.selectedImage = model.picture
            model.count += 1
            pictures[indexPath.row] = model

        }
    }
}

I try Codable way and NScoding both not working. Thanks!

1      

So here is the way I solved this challenge. But first, I want to clarify that I set it up so that each image retains its own view count. It looks like you are trying to combine all of the view counts under one key value.

Since we're just saving integers for the number of views, we can just use the UserDefaults class without having to use codable.

Here is what I did:

In DetailViewController file, I created a UserDefaults object and a savedCount property all the way at the top

var defaults = UserDefaults.standard
var savedCount = Int()

Under if let imageToLoad I attempted to load from a key even before saving. This will give me a value of 0 as explained in the lesson:

integer(forKey:) returns an integer if the key existed, or 0 if not

imageView.image = UIImage(named: imageToLoad)
savedCount = defaults.integer(forKey: "\(imageToLoad)")
navigationItem.setTitle(title: selectedImage!, subtitle: "Viewed: \(savedCount)")
savedCount += 1
defaults.set(savedCount, forKey: "\(imageToLoad)")

And regarding navigationItem.setTitle... I used aheze's idea from stackoverflow on how to add a subtitle to the nav bar

I hope this helped!

2      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.