My programming ramblings

Swift Alamofire tutorial uploading and downloading images

Posted on May 2, 2017 by Paul

This is a short tutorial about uploading and downloading images with Alamofire from an iOS, Swift 3, application.

I assume that you have the latest Xcode installed on your Mac, and that you know how to code small iOS applications in Swift 3.

I also assume that you have access to a server, ideally you have your own server with a domain name and a SSL certificate installed. If this is not the case, you can use a local Apache or NGINX web server. Personally, I use the free version of MAMPP which allows me to easily switch between Apache and NGINX if necessary. A good alternative to MAMPP is XAMPP. As a side note, macOS comes with an old version of Apache and PHP 5.3 already installed.

First, you need to install Alamofire. I found that the easiest approach to get started with Alamofire for iOS projects is to use CocoaPods. Open a Terminal and install CocoaPods:

1 sudo gem install cocoapods

The above command will use the outdated Ruby 2.0 that comes with macOS.

Optionally, if you want to use a more modern Ruby, you can use the Homebrew package manager:

Once you have CocoPods installed, open Xcode and create a new project, select Single View Application and be sure to select Swift in the language drop down list:

Close the Xcode project and, from a Terminal, go to the project folder. Assuming you’ve named your project “AlamofireExample” and that you’ve saved it on your Desktop:

1 cd ~/Desktop2 cd AlamofireExample

Now, create a new Podfile and open this in your preferred text editor:

1 pod init2 open Podfile

Change the content of the file from:

1 # Uncomment the next line to define a global platform for your project 2 # platform :ios, '9.0' 3 4 target'AlamofireExample'do 5 # Comment the next line if you're not using Swift and don't want to use dynamic frameworks 6 use_frameworks! 7 8 # Pods for AlamofireExample 9 10 end

to (see lines 2 and 9):

1 # Uncomment the next line to define a global platform for your project 2 platform:ios,'10.0' 3 4 target'AlamofireExample'do 5 # Comment the next line if you're not using Swift and don't want to use dynamic frameworks 6 use_frameworks! 7 8 # Pods for AlamofireExample 9 pod'Alamofire','~>4.4'10 end

save and close the file.

Now, execute the next command in Terminal:

1 pod install

From now on, you will use AlamofireExample.xcworkspace instead of the usual AlamofireExample.xcodeproj. Just double click on AlamofireExample.xcworkspace and it will open in Xcode.

Drag an image from your computer to the AlamoFireExample project and be sure to check Copy items if needed. You can use the same image as me, tree.png, if you wish. I will use this image to exemplify uploading an image from our iOS application.

In Xcode, select the Main.storyboard and drag an Image View to the center of the View Controller. I suggest to add some constraints to the Image View. First make sure it is aligned horizontally and vertically:

Next, set the image view to be 300x300 points:

Set the content mode of the image to Aspect Fit:

Next, we’ll need to get a reference to the image view from the Main.storyboard in our code. Select the view controller from the Main.storyboard and click on the double circle symbol in the top right corner of Xcode. This should open ViewController.swift in a second window to the right.

Now, click on the UIImageView, press CTRL and drag the line toward ViewController.swift. Leave it just above the viewDidLoad(). Chose a descriptive name, something like downloadImage and press Connect:

Import the Alamofire module in ViewController.swift:

1 importUIKit2 importAlamofire

If you see an error, simply build the project, after which Xcode will recognize the Alamofire module.

If you run the above code in the iPhone Simulator, this is what you should see:

Next, let’s write the image upload example. For simplicity we will use an image bundled with our application, the tree.png we’ve added earlier to our project. The same technique we’ll present here can be employed if you, for example, use an image from your device photos, you just need to add some boilerplate code.

First, we can get the URL of our bundled image with:

1 letimageURL=Bundle.main.url(forResource:"tree",withExtension:"png")

Usually, no server will let you upload an image without some form of authentication. For our example we’ll use a dummy user name and password:

1 letparameters=["user":"Sol","password":"secret1234"]

By default, iOS (the App Transport Security policy) won’t let you send HTTP requests to a server without a valid SSL certificate. If you use a local Apache or NGINX server for development, you usually don’t have a SSL certificate. In order to be able to use this local server, we need to add an exception for our localhost.

In Xcode, right click on Info.plist and select Open As source code. Copy the next lines just before the last closing dict tag:

For my machine, I have an Apache server running at http://localhost:8888 and I’ll save the PHP script that will receive the uploaded image in a file named upload_image.php. So, I will send the upload request to http://localhost:8888/upload_image.php. Be sure that you have write rights on your target server, otherwise the upload will fail.

Please note, that I don’t check for errors in the above PHP code. For illustration purposes, the code will send back the content of the $_FILES and $_POST PHP superglobals. Don’t use the above code on a production server!

Now, let’s write the Swift code that will upload the image bundled with the application:

Disclaimer:All data and information provided on this site is for informational purposes only. solarianprogrammer.com makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis. solarianprogrammer.com does not collect any personal information about its visitors except that which they provide voluntarily when leaving comments. This information will never be disclosed to any third party for any purpose. Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for understanding.