Why is my Swift function not printing from inside the dataTask closure?

44 views Asked by At

I am trying to learn about making http requests using Swift but for some reason i cannot get the getPosts() method to print anything. It keeps skipping over the dataTask and prints after it. I understand that the dataTask is happening asynchronously on a different thread but how would i go about printing this data onto the console?

Note: I am creating an instance and calling this method from a Obj-C main file but I do not see how that would affect this.

class EndpointInterface: NSObject {
    @objc var baseUrl:URL = URL(string:"https://api.publicapis.org")!
    
    @objc func getPosts() -> Void{
        let getPostsEndpoint:URL = URL(string: "/entries", relativeTo: baseUrl)!
        print(getPostsEndpoint.absoluteString)
        let getPostsRequest:URLRequest = URLRequest(url: getPostsEndpoint)
        let session = URLSession.shared
        let task = session.dataTask(with: getPostsRequest) {(data, response, error) in
            if let error = error {
                print(error)
              } else if let data = data, let response = response as? HTTPURLResponse {
                if response.statusCode == 200 {
                  print(data)
                } else {
                    print(response.statusCode)
                }
              }
        }
        task.resume()
    }
}

Thank You.

I have tried passing a completion handler

@objc func getPosts(completion: @escaping (NSData?) -> Void) -> Void{
        let getPostsEndpoint:URL = URL(string: "/entries", relativeTo: baseUrl)!
        print(getPostsEndpoint.absoluteString)
        let getPostsRequest:URLRequest = URLRequest(url: getPostsEndpoint)
        let session = URLSession.shared
        let task = session.dataTask(with: getPostsRequest) {(data, response, error) in
            if let error = error {
                print(error)
              } else if let data = data, let response = response as? HTTPURLResponse {
                if response.statusCode == 200 {
                  print(data)
                    completion(data as NSData)
                } else {
                    print(response.statusCode)
                    completion(nil)
                }
              }
        }
        task.resume()
    }

like so and

[e getPostsWithCompletion:^(NSData *data) {
                            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                            return;
                        }];

in main.m

0

There are 0 answers