Search code examples
jsonswiftapiurlsession

Swift UrlSession Not work inside UrlSession


so i wanna parse json api, but i the way i get that param to parse i need to fetch another json (which is working), and since i cant put that data param for my 2nd json api into global var so i can just put it into another func, i have this idea that i parse my 2nd json api inside the 1st urlSession, but i always get a nil callback,

override func viewDidLoad() {
    super.viewDidLoad()
    
    
    getRoom()
    
    
}

func getRoom() {
    
    guard let url = URL(Some url) else {return}
    
    print(url)
    URLSession.shared.dataTask(with: url) { data, resp, err in
        guard let data = data else {return}
        
        do{
            let decoder = JSONDecoder()
            let room = try decoder.decode(User.self, from: data)
            self.dataClient = [room].compactMap{$0!.data}
            self.DATA = [room]
            print("ini dataClient 🪕\(self.dataClient)")
            let roomid = self.dataClient[0].RoomID
            self.roomId = roomid
            print(self.roomId)
            
            DispatchQueue.main.async {
                 checkRoom()
            }
        }catch{
            print(err!)
        }
    }.resume()
    
}

func checkRoom() {
    
    if self.roomId == 0 {
        print("roomId nil")
    }else if self.roomId != 0{
        print("ini room id \(self.roomId)")

        guard let urlRoom = URL(some url) else {return
        
        URLSession.shared.dataTask(with: urlRoom) { (data, resp, err) in
            guard let data = data else {return}
            do{
                let decoder = JSONDecoder()
                let roomAv = try decoder.decode(User.self, from: data)
                self.DATA = [roomAv]
                print("ini boolnya 🎸 \(self.DATA[0].success)")
                print("Success")
            }catch{
                print("damn😭") // this line always get called 
            }
        }.resume()
    }
}

can anyone tell me any ideas? the reason i put the 2nd urlsession inside 1st urlsession because i need that (self.roomId) for my param in my 2nd Json api.

and when i try to separate both urlsession func in my checkRoom() alwasy called "roomId Nil"


Solution

  • I wouldn't make a call within a call personally. That's asking for trouble. Just call the first endpoint, get the data from it and pass in whatever you needed from that into the second call in your logic controller.

    Quasi code:

    import Foundation
    
    class Test {
        func getRoom() {
            getFirstCall { [weak self] (foo) in
                self?.getSecondCall(someArg: foo) {
                    // Handle data here.
                }
            }
        }
        
        func getFirstCall(completion: @escaping (_ somethingToReturn: String) -> ()) {
            
            guard let url = URL(string: "Some URL") else { return }
            
            URLSession.shared.dataTask(with: url) { data, response, error in
                // Logic to ingest data.
                completion("foo")
            }.resume()
        }
        
        func getSecondCall(someArg: String, completion: @escaping () -> ()) {
            
            guard let url = URL(string: "Some URL 2") else { return }
            
            // Use "someArg" however you need in this call. queryParam, body, etc.
            
            URLSession.shared.dataTask(with: url) { data, response, error in
                // Logic to ingest data.
                completion()
            }.resume()
        }
    }