[SOLVED] Working button for next page in API call SwiftUI

Issue

In my app I’m trying to get this next button to keep getting new pages. When i press next 501 loads and when I press prev 499 loads. I’m understanding that it’s because comicNumber is set to 500, but having troubles with how I can make it keep going (502,503 etc).

This is my api call


struct Comic: Codable {
    var month: String
    var num: Int
    var link: String
    var year: String
    var news: String
    var safe_title: String
    var transcript: String
    var alt: String
    var img: String
    var title: String
    var day: String
}



enum ApiError: Error {
    case dataIsNil
}

class ApiCall {
   var comicNumber: Int
    
        
    init(comicNumber: Int) {
        self.comicNumber = comicNumber
    }
        
    func getComic(completion: @escaping (Result<Comic, Error>) -> ()) {
        
        guard let url = URL(string: "https://xkcd.com/\(comicNumber)/info.0.json") else {return}
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                print(error)
                completion(.failure(error))
                return
            }
            guard let data = data else {
                print("data is nil")
                completion(.failure(ApiError.dataIsNil))
                return
            }
            do {
                let comic = try JSONDecoder().decode(Comic.self, from: data)
                //                print(comic)
                DispatchQueue.main.async {
                    completion(.success(comic))
                }
            } catch {
                print(error)
                completion(.failure(error))
            }
        }
        .resume()
    }
    
    func getNextComic(completion: @escaping (Result<Comic, Error>) -> ()) {
        guard let url = URL(string: "https://xkcd.com/\(comicNumber)/info.0.json") else {return}
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                print(error)
                completion(.failure(error))
                return
            }
            guard let data = data else {
                print("data is nil")
                completion(.failure(ApiError.dataIsNil))
                return
            }
            do {
                let comic = try JSONDecoder().decode(Comic.self, from: data)
                DispatchQueue.main.async {
                    completion(.success(comic))
                }
            } catch {
                print(error)
                completion(.failure(error))
            }
        }
        .resume()
    }
    
    func getPrevComic(completion: @escaping (Result<Comic, Error>) -> ()) {
        guard let url = URL(string: "https://xkcd.com/\(comicNumber)/info.0.json") else {return}
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                print(error)
                completion(.failure(error))
                return
            }
            guard let data = data else {
                print("data is nil")
                completion(.failure(ApiError.dataIsNil))
                return
            }
            do {
                let comic = try JSONDecoder().decode(Comic.self, from: data)
                DispatchQueue.main.async {
                    completion(.success(comic))
                }
            } catch {
                print(error)
                completion(.failure(error))
            }
        }
        .resume()
    
    }
}

And this is my View

struct ComicContainer: View {
    
    @State var comic: Comic?
    @State var comicNumber = 500
        
    var body: some View {
        ZStack {
            VStack {
                
                NavigationLink(destination: ComicDetailView(), label: {
                    AsyncImage(url: URL(string: comic?.img ?? "Hello")) { image in
                        image
                            .resizable()
                            .scaledToFit()
                    } placeholder: {
                        Color.purple.opacity(0.1)
                    }
                    .padding()
                })
                    .onAppear {
                        ApiCall(comicNumber: comicNumber).getComic{ result in
                            switch result {
                            case .success(let comic):
                                self.comic = comic
                            case .failure(let error):
                                print(error)
                            }
                        }
                    }
                    .toolbar {
                        ToolbarItemGroup(placement: .bottomBar) {
                            CustomButton {
                                ApiCall(comicNumber: comicNumber - 1).getPrevComic{ result in
                                    switch result {
                                    case .success(let comic):
                                        self.comic = comic
                                        print(comic.num)
                                    case .failure(let error):
                                        print(error)
                                    }
                                }
                            } content: {
                                Text("Prev")
                            }
                            Spacer()
                            Text("Comic num: \(comic?.num ?? 0)")
                                .padding()
                            Spacer()
                            CustomButton {
                                ApiCall(comicNumber: comicNumber + 1).getNextComic{ result in
                                    switch result {
                                    case .success(let comic):
                                        self.comic = comic
                                        print(comic.num)
                                    case .failure(let error):
                                        print(error)
                                    }
                                }

                            } content: {
                                Text("Next")
                            }
                        }
                    }
                    .navigationBarTitle("\(comic?.title ?? "title")")
            }
        }
    }
}

I tried so the comicNumber gets + 1 or – 1 when you press next or prev buttons

 ApiCall(comicNumber: comicNumber + 1).getNextComic{ 

I also tried with + 1 inside the api but its just the same.

guard let url = URL(string: "https://xkcd.com/\(comicNumber + 1)/info.0.json") else {return}

Does anyone have any guidance on how I could get this to work or what I’m doing wrong? I’m learning Swift and would really appreciate some help<3

Solution

comicNumber is being stored in too many places. In SwiftUI we try to keep a "single source of truth". Keep an instance of ApiCall() as a member of your view so that comicNumber stays updated:

struct ComicContainer: View {
    
    @State var comic: Comic?
    var api = ApiCall(comicNumber: 500)
        
    var body: some View {
        ZStack {
            VStack {
                
                NavigationLink(destination: ComicDetailView(), label: {
                    AsyncImage(url: URL(string: comic?.img ?? "Hello")) { image in
                        image
                            .resizable()
                            .scaledToFit()
                    } placeholder: {
                        Color.purple.opacity(0.1)
                    }
                    .padding()
                })
                    .onAppear {
                        apiCall.getComic{ result in
                            switch result {
                            case .success(let comic):
                                self.comic = comic
                            case .failure(let error):
                                print(error)
                            }
                        }
                    }
                    .toolbar {
                        ToolbarItemGroup(placement: .bottomBar) {
                            CustomButton {
                                apiCall.getPrevComic{ result in
                                    switch result {
                                    case .success(let comic):
                                        self.comic = comic
                                        print(comic.num)
                                    case .failure(let error):
                                        print(error)
                                    }
                                }
                            } content: {
                                Text("Prev")
                            }
                            Spacer()
                            Text("Comic num: \(comic?.num ?? 0)")
                                .padding()
                            Spacer()
                            CustomButton {
                                apiCall.getNextComic{ result in
                                    switch result {
                                    case .success(let comic):
                                        self.comic = comic
                                        print(comic.num)
                                    case .failure(let error):
                                        print(error)
                                    }
                                }

                            } content: {
                                Text("Next")
                            }
                        }
                    }
                    .navigationBarTitle("\(comic?.title ?? "title")")
            }
        }
    }
}

And handle the updating of comicNumber within the view model (ApiCall):

class ApiCall {
   var comicNumber: Int
    
        
    init(comicNumber: Int) {
        self.comicNumber = comicNumber
    }
        
    func getComic(completion: @escaping (Result<Comic, Error>) -> ()) {
        
        guard let url = URL(string: "https://xkcd.com/\(comicNumber)/info.0.json") else {return}
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                print(error)
                completion(.failure(error))
                return
            }
            guard let data = data else {
                print("data is nil")
                completion(.failure(ApiError.dataIsNil))
                return
            }
            do {
                let comic = try JSONDecoder().decode(Comic.self, from: data)
                //                print(comic)
                DispatchQueue.main.async {
                    completion(.success(comic))
                }
            } catch {
                print(error)
                completion(.failure(error))
            }
        }
        .resume()
    }
    
    func getNextComic(completion: @escaping (Result<Comic, Error>) -> ()) {
        // this
        comicNumber += 1
        getComic(completion: completion)
    }
    
    func getPrevComic(completion: @escaping (Result<Comic, Error>) -> ()) {
           // this
           comicNumber -= 1
           getComic(completion: completion)
    }
}

Answered By – atultw

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.