Getting Data From a URL in Swift

One building block that I stumbled over when building EdiTravel, my first ever iOS app, was the complexity to performing network calls and the difficulty to see whether it was actually returning the data before crashing my app when it failed.

For way too long I was using the URLSession Method

let urlString = MyURL
let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
   if error != nil 
   {
   // Deal With the Error
   }
   else 
   {
      do 
      {
      // Run Code From Data
      }
   }
}.resume()

Yes. Okay. It is hideous. I was a Swift newbie, reading, copying, modifying and pasting code from sites. I decided to fix this once and for all, by making my own function

getDataFromURL()

First, you are going to need CocoaPods – Getting Started With CocoaPods – It is fairly easy to install and I managed it fairly quickly with little Xcode Experience. Next, you are going to need to add and install SwiftHTTP to your project –

pod 'SwiftHTTP'

Head to Xcode, File -> New -> File -> Swift File -> <Pick a Folder> and select all Targets you wish to use this function with then Create. Now we want the file to look like this:

You’ll see above what the print functions actually return in the console – A lot of useful data including the full JSON response! Whats better here is that if there is an error code from your URL the app won’t crash, you can present an error message to the user and fire a command to Slack or another tool that a URL had a failure

Got something to add to the post? Did you find the code useful, let me know in the comments below!

Alex Written by: