In this short introduction to networking in iOS, we will access images from Flickr. To start, go to the Flickr API web page and create an API Key for your app. Once you have your key created, let’s start by creating a new Single View Application in Xcode. In the storyboard add an image view, a label and a button. Put the necessary constraints and then connect the UI elements to our view controller. Create two outlets for the image view and the label, and an action for the button. The action will only serve one purpose: call the method that gets the images from Flickr.
In the view controller class, make sure to assign the API Key you created earlier to the key variable. The gallery_id represents just a sample gallery I chose but you could use yours if you have one. The skeleton code looks like this:
Let’s start writing our networking logic by grabbing the singleton instance of NSURLSession and by creating the URL and an instance of NSURLRequest. You will notice we hard coded the URL, but in general it is considered good practice to start with a base url and then append API parameters from a dictionary containing all the parameter key-value pairs to construct the final URL. However, we will not cover this topic now, so let’s see how the initialization looks like:
In the next step, using the session and request, we instantiate the task for grabbing an image from Flickr:
In the completion handler, we parse the JSON response data and turn it into usable data:
Since our request will return JSON for multiple images in our gallery, we just grab one of the images:
Then we grab the selected image’s title and URL:
If there is data at the URL, then we update the photoImageView and photoTitle:
At the very end of the class, right after the last curly brace that closes the task initialization, write the code to execute the task. We are now ready to execute our task and see the result:
If you got everything right, you should see a similar screen in your simulator or on your device:
You can do more research into the Flickr API and implement new features such as being able to search for a specific user or image, instead of randomly displaying one.