swiftapinsurlsessiondatatask

datatask not executed, request is null


import Foundation

let headers = [
    "x-rapidapi-key": "myKey",
    "x-rapidapi-host": "movie-database-imdb-alternative.p.rapidapi.com"
]

let urlR = URL(string: "https://movie-database-imdb-alternative.p.rapidapi.com/?i=tt4154796&r=json")

var request = URLRequest(url: urlR!)

request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared

let dataTask = session.dataTask(with: request) { data, response, error in
    print(data ?? "data")
    print(response ?? "response")
    print(error ?? "error")
}

dataTask.resume()

The code inside datatask is not executed and even if i check with debugger and breakpoint, it would be skipped. Someone know why?


Solution

  • There's nothing wrong with your code, and there's an easy way to prove it: unit tests !

    import XCTest
    class DataTaskTests: XCTestCase {
        var dataTask: URLSessionTask!
        func testDataTask() throws {
            let headers = [
                "x-rapidapi-key": "myKey",
                "x-rapidapi-host": "movie-database-imdb-alternative.p.rapidapi.com"
            ]
    
            let urlR = URL(string: "https://movie-database-imdb-alternative.p.rapidapi.com/?i=tt4154796&r=json")
    
            var request = URLRequest(url: urlR!)
    
            request.httpMethod = "GET"
            request.allHTTPHeaderFields = headers
    
            let session = URLSession.shared
            let expectation = expectation(description: "testDataTask")
            dataTask = session.dataTask(with: request) { data, response, error in
                expectation.fulfill()
            }
    
            dataTask.resume()
            wait(for: [expectation], timeout: 30.0)
        }
    }
    

    Saying :

    The code inside datatask is not executed

    Makes me think that maybe you were trying this code in a playground