How to Make a Simple Flickr App Using Alamofire, SwiftyJSON and Swift 1.2

This tutorial is meant to teach you the basics of accessing APIs using the Swift Programming language and the Alamofire and SwiftyJSON libraries. Alamofire makes accessing APIs quick and (somewhat easy). You don’t need to know anything to use this tutorial, but it will definitely help to know some programming and the concepts behind an API. For example, I am not going to go into a ton of detail about JSON objects and Dictionarys, but hey, if you are trying to learn then you should be Googling everything new you come across. Let’s get started.

What is an API?

API stands for Application Programming Interface. APIs let us interact with other programs in order to exchange information. Think about how you interact with people. You come up to someone, shake their hand, ask for their name, and try to get some information about them like where they are from etc. An API works in kind of the same way. Companies like Flickr make programming interfaces so developers like ourselves can make applications for their websites. They want access to their data to be easy so more people make more awesome apps for their site, so what they try to do is provide an interface that can easily communicate with any other application or interface.

So we are going to be using the Flickr API. We can see from the Flickr API page that we are given some things we can do with the API. Let’s go around and mess with the search for photo API. Type in some stuff to some of the boxes and choose JSON from the drop down menu. We should get back something that looks like this.

That is a lot of junk, isn’t it? That is called a JSON object. I would explain it here, but I find this explanation to be better than any garbage I could probably come up with.

Anyways, so the gist of this app is that we are going to send a message about something we want to find, and it is going to send us back a list of photos. From that last we are going to randomly display one of those photos. Hopefully it will teach you enough about APIs that you can go learn more about them and use that big, beautiful creative mind of yours to build something great.

Getting Started

First we need to open Xcode and select File > New > Project…  from the menu. We are going to choose Single View Application for the Application type.

Screen Shot 2015-06-14 at 3.35.58 PM

 

Next we need to decide what to call our App. I chose FlickrPickr because it is kind of catchy and I was impressed with my ability to be that clever. Some of our instructions might refer to that name again so you might want to keep it, but you can call the program what you want. I also chose Swift as my language and iPhone as my target. You could turn Core Data on or off. We won’t use it in these tutorial, but I usually keep it on because I use it often and it is much harder to add after this step.

Screen Shot 2015-06-14 at 2.26.29 PM

 

Installing Swift Libraries with CocoaPods

Next comes kind of the intimidating part. We need to install some libraries for our program. The first library we are going to install is called Alamofire. Alamofire is an HTTP networking library that will help us talk to Flickr. We also need to install SwiftyJSON. Remember that big and ugly looking JSON object we saw before? Well we need to iterate through that to get those pieces of data that we need to get our picture. SwiftyJSON will help us with that.

We are going to use CocoaPods to install these frameworks. CocoaPods is a dependency manager for iOS. What does that mean? Well our project depends on code from Alamofire and SwiftyJSON to run. CocoaPods is going to install that code for us.

To do this, we need to open up the Mac OS X program Terminal. In the terminal, we want to write this command and press return to install CocoaPods.

You will probably have to type in your password. In the Terminal, you will not see your password as you type it. That is ok! No reason to panic. Just type it as normal and press return when you are finished.

Next we need to navigate to the root folder of our project. There are two major commands we need to understand to navigate to our folder. The command cd navigates us to a folder and the command ls (that is an L) tells us what is in that folder. So check the path of the folder and us it to get us to the root of that folder. My project is in my XcodeProjects folder. So I am going to type this command to get to the root of our folder.

Let’s type “ls” to make sure we are in the right place.

Ok, by looking at our folder contents, I can tell I am in the right page. If you go to far or get lost, you can just type cd to get you back home, of cd .. to go back up a level.

Now we need to make a new Podfile. Once you are in the right place type:

This will create a new file called Podfile in our root folder. Let’s find that in the finder and let’s right click and choose Open With. Find Xcode and use Xcode to open it. Why? Because TextEdit can sometimes mess up the formatting, with our Podfile can be picky with. Let’s replace the file with these lines:

When we are done, save the file and go back to the Terminal. Still in the project root folder, type in:

This might take a minute, but when you are done you will see a message about closing Xcode and only opening the project using the Workspace and not the project file. That is the white file, and not the blue file. So no more opening Xcode and picking the project, we need to double click that white file! Let’s go ahead and do that now.

Building the Layout

So let’s go to our Navigator and click on Main.storyboard.

Screen Shot 2015-06-15 at 11.45.23 AM

 

Layouts in Xcode can be a little tricky, so we are going to open a preview of our layout so we can see what Xcode thinks the layout will look like with the App running. Let’s click on this Venn diagram looking thing here in the top right.

Screen Shot 2015-06-15 at 11.56.11 AM

We should see some code appear. Next let’s click on the menu that says Automatic. Scroll down to where is says preview and choose Main.storyboard. Now we have how layout creator and our layout preview side by side. If you have a smaller screen, you might want to consider using spaces to manage these windows.

Your window should look something like this.

Your window should look something like this.

Next we are going to change our background color. This isn’t a necessary step, but I think it makes working with the layout a little easier and you might as well if you are starting out. Let’s do that by clicking on the background of our layout, and the clicking on the Attributes Inspector. It appears on the right of the screen. Here is a picture to help you find it.

Attributes Inspector and Change Background

Attributes Inspector and Change Background

Click on Background and choose a color that you like. For this exercise, I am choosing Light Gray Color.

Now we need to add an Image View to our View. This is where our picture will go once we retrieve it from Flickr. Click on the search box in the bottom right and type in image. You should see Image View appear. Drag it into the middle of the view.

Finding the Image View

Finding the Image View

Now we are going to look in the bottom corner of our layout builder. We see three buttons. The first is for alignment. The second is for pinning buttons in place, and the third is about resolving layout issues. Let’s click the second one and we are going to put 0 in for our constraints to either side of the Image View and 0 for the constraint on top. This will fill our image to the sides and top of the screen.

The red lines are the values we changed.

The red lines are the values we changed.

Next we want to Update Frames when we click out of here. Select Items of New Constraints and press Add 3 Constraints. Now we should see our Image View shrink up a bit. Drag the bottom of the Image View down to fill up 2/3 – 3/4 of our screen or so. Then we are going click on that third button to Reset to Suggested Constraints.

Reset to Suggest Constraints

Reset to Suggest Constraints

Now we should see something that looks like this:

Hopefully you are here.

Hopefully you are here.

Now set the Mode to Aspect Fit for the Image View. This will make sure our images fit when we download them.

Set the Image View to Aspect Fit

Set the Image View to Aspect Fit

Now we need to add a Text Field to our layout. Go back to the bottom right of the screen and type in text where you typed in image. Drag the Text Field to a the space a little below our Image View. When you do, a blue line should appear when it is centered. Drop it there.

Next we want to hold down control and drag the Text Field to our Image View. We are given a few options in doing so. We want to check Vertical Spacing and Center X. You can select multiple options at once by holding down the shift key or by control dragging twice. I won’t tell anyone if you have to do it twice. You should see some blue lines appear. Those are our new constraints. We can adjust these by clicking on them if you want to change things later.

Making some new constraints.

Making some new constraints.

Control dragging is how we add constraints from one item to another. We can also constrain items to the view.

Our Text Field is looking a little small, so we are going to click on the Pin button again and give it a fixed width of 150. This time, we are going to choose All Frames in Container since we added the two before this.

Giving our Text Field a width.

Giving our Text Field a width.

Now we should have our layout looking nice and neat.

Screen Shot 2015-06-15 at 12.40.29 PM

 

Next we are going to go back to that bottom right and look for a Button. Let’s drag that Button to the space in between the Text Field and the bottom margin. Double Click on it to change the text to something like Search.

Next we want to control drag it again to the Text Field this time and create constraints again so it sits where we need it. I am not going to hold your hand this time! Follow the steps from last time and see if you can do it! And remember, you can use the third button on the bottom right of the layout menu to update your frames. In the end you should have something like this.

Your layout

Your layout

Connecting the layout to the View Controller

Next, we are going to change out of Preview mode and look at out code. Let’s go back to our Preview menu and let’s switch back to Automatic. We should see our code for the View Controller. We now need to add our three new items to our View Controller. We do this by holding down control and dragging each element into our View Controller above our viewDidLoad method. A window will pop up. Let’s name this Image View variable imageView and make sure we choose Outlet.

Adding Image View to the Controller

Adding Image View to the Controller. Ignore the two extra import statements for now.

Let’s do the same with the Text Field. Let’s call the Text Field searchTextField. When we are done, Xcode should have generated the following code.

Now we need to add an outlet for our button to do something when we click it. Hold down control and drag the button to under the didReceiveMemoryWarning function (you can delete that function if you want, we aren’t going to use it). Next we need to change it to an Action and we will call it searchClick.

Adding an action to our button.

Adding an action to our button.

We should now see that Xcode has generated this code.

Our layout is now complete and the boring stuff is over. Let’s dive into our code.

Starting Our Code and Retrieving Data from Flickr

If you don’t still have the View Controller open or if you want to work with a bigger screen, you can go over to the Navigator and click on our ViewController. For the sake of this simple project, we are going to write all of our code here. Although retrieval code should always be in the Controller class, we might be able to write some of our code dealing with adding strings in another utility class. For the sake of this small exercise, we are not going to do that. ANYWAYS back to lesson at hand. Click on your ViewController class.

Screen Shot 2015-06-14 at 4.19.29 PM

The folder in our top left is our navigator icon. Click on that and drop the FlickrPickr folder down and then click on ViewController.swift. Now we should finally see some code. Let’s add these two lines after import UIKit.

Now Xcode might yell at you and tell you it can’t find one of these modules. Tell Xcode to calm down by building the project. The error should go away.

Next we need to get an API key. Let’s go back over here and click on API key. We will be promoted to sign into Yahoo. I had a few issues where I had to go back and click the get API button key twice since I didn’t have a Flickr account and Yahoo takes you back to the home page after signing in.

After getting the API Key, we want to add it to our project. We are going to set up some static variables in our View Controller. Let’s do this between our Outlet variables and the viewDidLoad method.

The first variable is your API Key. I didn’t include my key! You will have to include your own that you got from Yahoo. The next string is our URL. This URL is the access point for the Flickr API. The next method is our API method, which is in this case the photos search method. The next 2 deal with having Flickr return the data as a JSON object, and the last variable gives us only public photos back. You will see how we use these in a minute.

Now we are going to add some code to make it so we can dismiss our keyboard when we press return. First, we want to extend the View Controller class with UITextFieldDelegate. This let’s our View Controller take control of our keyboard, and can make it disappear when we press return. We do this by adding a comma and UITextFieldDelegate to the top of our class, where our class name is. It should now look like this.

In the viewDidLoad function, we are going to add self.searchTextField.delegate = self.

And then we want to add this method to our class.

Now when we press return, it’ll dismiss our keyboard.

Next we are going to add a function that will take a URL from a string and put it into our Image View. Make a new function with this code.

This function takes a string. It then does something a little strange. Since we are updating our Image View from a URL, we want to run this function in another thread. It might take a few seconds to access our image. If we don’t use dispatch_async, then it will freeze up our program! We can’t have that. So we dispatch our function to another CPU thread.

Then we make our String into a NSURL and we get the data from that URL. If the data is not equal to nil, we load it to our Image View, and if it is, we try again. BAD CODE ALERT. Well maybe not bad code, but there is probably a more graceful way of handling if the data is not nil. What if there is no picture there? This could enter an infinite loop. But hey, it works for this tutorial. You will probably want to think of some more graceful ways of handling the data retrieval error in the future.

Next, we are going to make a function that uses Alamofire to get a String that we will feed into the class we just made. Let’s make a new class and we will add the following code to it. We will call the class urlToImageView.

First we are going to get a random number between 1 and 100. We are going to do this so we can get a random image back from the first page of data that is return to us from Flickr.

But Clinton, wouldn’t that mean that we aren’t truly getting a random image back, but just an image from the first page of results?

Hey GUY. This is my tutorial and I don’t need your lip! But yes, you are correct. It works well enough for this tutorial and that is what I am sticking with. The API might have a better way of doing it, but the main objective of this tutorial is to teach you to use Swift with Alamofire and SwiftyJSON, not to teach you the full extent of the Flickr API.

Next we see our request. Let’s go over some of the parts.

  • .GET – This is the type of request we are sending. We want information back, so we are GETting it. If we wanted to post something, we would use something like .POST. But that is another tutorial for another day.
  • Parameters – These are the parameters for our API request. Here we put in our type, the privacy_filter, and all the other good stuff. It is what will appear at the end of our URL for our request. You have seen them 100 times before in other URLs. They are that funky language at the end that looks something like &page=100.
  • responseJSON – This is our response type. Since we want a JSON back, we request it with responseJSON.

Next is what we call a callback function. It is what happens after we request the data. First we check if our data is nil. Here, that is all we do. If you were making a real App, then you would want to have an else statement that would handle what happens when no data is returned. You might also want to have something like if(error != nil) to handle our errors. Keep these in mind when making your app! Part of what goes into a good App is gracefully handling mistakes! Different APIs might make for different challenges.

Next we are going to use SwiftyJSON’s JSON class to get the parts of the data we need. The JSON class basically turns the data into an a Dictionary. This allows us to access the parts of the data that we need to build our URL for our picture. Here is a diagram of how it breaks down. Look at the code var farm:String = innerJson[“photos”][“photo”][random][“farm”].stringValue. Let’s pretend that the random is equal to 1.

JSON Explained

JSON Explained

We only want to get one picture, but we are returned a HUGE string of pictures. So we got to move down the ladder a bit. We do this by first accessing “photos”, which gives us pretty much all of the data. We need to go deeper! Next we access “photo”, which gets rid of a few things, but still, we need to go deeper! Next we get to 1, which brings us just the second photo data. Why does 1 give us the second set of data? Because it uses zero-based indices. These means we start the count from 0. Now we are at our random picture. All we need to do is get the values for our picture string. Here we can see that “farm” is 6.

Hopefully that explains a little bit of what is going on with that code, and how Alamofire and SwiftyJSON can bring you back data that you can work with. Every API and even functions within that API work a little different, so you are going to have to spend some time in that JSON object to figure out how to get access to what you need. There are a lot of programs you can use to better view JSON files. The one here is called JSON Accelerator. Many create classes from JSON objects, but sadly, this one does not nor have I found another one that does so for Swift. Hint, hint JSON Accelerator.

Then we take our parts and turn it into a String that will be the URL for our picture. If you want, you can print this String out when you run the program and copy it into a browser. And then finally we will take our URL String and send it to our other function. Let’s try running the code. Type “hello world” into the Text Field and press Search.

The finished product.

The finished product.

Wow, look at that. This App would be better with an Activity Indicator, but that is for another Tutorial. As usual, let me know if you have any questions in the comments.Here is the GitHub code, minus my API key.

FlickrPickr Github

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *