Home > front end >  SwiftUI Combine - I want to load data from api page by page
SwiftUI Combine - I want to load data from api page by page

Time:11-13

var page_num = 1

guard let url = URL(string: "http://127.0.0.1/api/v4/fetch_records/?page=\(page_num)")  else { return }
        
NetworkManager.GET(url: url)
    .decode(type: GlobalData.self, decoder: JSONDecoder())
    .subscribe(on: DispatchQueue.global(qos: .background))
    .receive(on: DispatchQueue.main)
    .sink{ (completion) in

    } receiveValue: { [weak self] (returnedData) in
        if returnedData.status == "success" {
            for record in returnedData.data {
                print(record)
            }
        }
    }

And the data from the server is like this:

{
    "page": 1,
    "total_pages": 10,
    "hasMore": true,
    "status": "success",
    "data": [{
        "id": 23409,
        "record_id": "P06TYUQZ",
        "money": "1.00",
        "date": "2022-10-24",
    }]
}

When the hasMore is true, the page_num = 1 and make the next page request until hasMore is false, how can I do that? Hope you guys can help me out.

CodePudding user response:

You could try using a recursion approach, something like this, to fetch all pages, page by page:

func fetchAllPagesFrom(_ page_num: Int) {
    guard let url = URL(string: "http://127.0.0.1/api/v4/fetch_records/?page=\(page_num)")  else { return }
    // ....
    if returnedData.hasMore {
        // pace/delay the next call here if need be
        fetchAllPagesFrom(page_num   1)  // <-- fetch another page
    } else {
        return // <-- all done
    }
}
 

Use it like this:

 fetchAllPagesFrom(1)

Note, Apple requires https, unless you specifically change your "NSAppTransportSecurity" in your Info.plist

  • Related