0

I have a method which retrieves data from an API request:

    let session = URLSession.shared
    let url = URL(string: "http://eventregistry.org/json/article?conceptUri=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FAfghanistan&lang=eng&action=getArticles&articlesSortBy=date&resultType=articles")!

    let task = session.dataTask(with: url) { (data, _, _) -> Void in
        if let data = data {
            print(JSON(data: data))
            completion()
        }
    }
    task.resume()

The link works perfectly when accessing through a browser, however when debugging line by line in XCode, none of the code within the let task = session.dataTask is executed and so the print is not printed within the log.

I am running through emulator and my laptop has internet, im just not sure why this is not working.

Does anyone understand why?

5
  • When you say "debugging line by line", are you letting the runloop run? Commented May 15, 2017 at 18:56
  • @Ssswift Sorry, this wasn't set. It is now executed but for some reason the JSON retrieved is null? Although when making the request in browser it retrieves all of the data from the request Commented May 15, 2017 at 18:58
  • I pasted this into a new project in Xcode, changed the print/completion lines to a simple NSLog of data.count (since I don't know what your "JSON" class/struct is), and changed "http" to "https" (as per Xcode's warning), and ran it. It shows 15594 bytes returned. I even put a breakpoint in the completion handler, and it was triggered. Can you be more specific about exactly how you're running this in the debugger? Commented May 15, 2017 at 19:08
  • @Ssswift Hmmm mine returns 70 bytes :/ ? The JSON class is provided by a library "SwiftyJSON" I'm running this using an emulator which calls this function on viewDidLoad() I just don't understand at all why this isn't working when it's working for you? Commented May 15, 2017 at 19:23
  • Have you tried a project that doesn't require an emulator? It's sounding suspiciously like your problem is not the code, but something the emulator is doing to your network requests. Commented May 15, 2017 at 20:30

1 Answer 1

1

Try writing it this way. and also try to avoid the "Void"

First you need to make the urlRequest.

Example:

let urlRequest = URLRequest(url: URL(string: "Your url/API links here")!)

let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in {

     //Your codes here
   }

task.resume()
}

Hope it helps. If you need any further explanation, I will post a sample answer to retrieve the Registry Articles.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.