URLSession doesn't work with GET API call

227 views Asked by At

When I try to run XCUTest test, it calls the API but I cannot print or get the API response. I didn't see any errors while building or running the test. Xcode 14

This is the code in the UI test.

        let temp = APIHelpers()
        temp.requestAPIInfo {(apiResult) in
            print(apiResult)
        }

This is the APIHelpers

import Foundation

struct Example: Decodable {
    let userId: Int
    let id: Int
    let title: String
    let completed: Bool
}
 
struct APIHelpers {
    
    var resourceURL: URL
    let urlString = "https://jsonplaceholder.typicode.com/todos/1"
   
    init() {
        resourceURL = URL(string: urlString)!
    }
    
    //create method to get decode the json
    func requestAPIInfo(completion: @escaping(Result<Example, Error>) -> Void) {
        var request: URLRequest = URLRequest(url: resourceURL)
        request.httpMethod = "GET"
        
        let dataTask = URLSession.shared.dataTask(with: resourceURL) { (data, response, error) in

            guard error == nil else {
                print(error!.localizedDescription)
                print("stuck in data task")
                return
            }

            let decoder = JSONDecoder()

            do {
                let jsonData = try decoder.decode(Example.self, from: data!)
                completion(.success(jsonData))
            } catch {
                print("an error in catch")
                print(error)
            }
        }
        dataTask.resume()
    }
}
0

There are 0 answers