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 -> and select all Targets you wish to use this function with then Create. Now we want the file to look like this:

func getDataFromURL(path: String, headers:[String:Any], completion: @escaping (JSON) -> Void)
{
	HTTP.GET("\(path)", parameters: headers) { 
		
		response in
		
		if let err = response.error {
			print("error: \(err.localizedDescription)")
			return //also notify app of failure as needed
		}
		else
		{
			print("Response Was: \(response.description)")
			print(response.data)
			completion(JSON(response.data))	
		}
	}
}

func LoadData()
{
	getDataFromURL(path: "", headers: [ : ])
		{
			data in
			// Use the returned JSON data
		}
}

This is the output from using https://jsonplaceholder.typicode.com as the URL, ‘/comments’ as the Path and ‘”postId” : 1’ as the headers

Status Code:
200

Headers:
Content-Type: application/json
Date: Fri, 17 May 2019 19:55:58 GMT
x-powered-by: Express
access-control-request-method: GET
Server: cloudflare

Payload:
{"postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et" }, { "postId": 1, "id": 3, "name": "odio adipisci rerum aut animi", "email": "Nikita@garfield.biz", "body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione" }, { "postId": 1, "id": 4, "name": "alias odio sit", "email": "Lew@alysha.tv", "body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati" }, { "postId": 1, "id": 5, "name": "vero eaque aliquid doloribus et culpa", "email": "Hayden@althea.biz", "body": "harum non quasi et ratione\ntempore iure ex voluptates in ratione\nharum architecto fugit inventore cupiditate\nvoluptates magni quo et"}
2230 bytes

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!