Cloudinary with Swift(iOS)
Tags: ios, swift, mobile, programming
Published: 2022-12-23 20:23:09

Hi! Adi here. Been a while since I wrote. Switched jobs a few months ago, and it took most of my capacity, so I wasn't able to write. I’ve joined a great company called Cloudinary, and it is part of the reason I’m writing this blog. So let’s get started.

## The Problem!
In one of my previous jobs, I was responsible for an application that allows you as the user to download images into their phone and set them as a background for the home screen, lock screen, or both.
This application requires pulling big JSON files with all the image information, each image having multiple fields such as title, URL, created date, etc…

On the main screen, I had to present a thumbnail (A thumbnail is a small image representation of a larger image) of each image.
Tapping a thumbnail will direct the user to a screen where the image is shown full screen.

These 2 screens already required multiple versions of the same image. Since you can't present a full-screen image with a thumbnail image because you’ll get a pixelated result which yields a bad user experience. On the other hand, We don't want to present the full-screen image on the main screen (where we show many images on a screen) because it’ll cause a long load time of the screen. Which is again a bad user experience.

Other than that, each image has various sizes that we need to present, and let us not forget that the application supports multiple devices with different screen sizes, iPhones, iPads, and iPods which require different sizes of the image.

So how can we handle this? We have one image, but we need it in many different sizes. We can take it on the client side and manipulate the image on the device but that won't be efficient.

We can ask our server-side (if we have one) to give us multiple URLs for each image but that will make the JSON response huge and hard to handle.

This is where Cloudinary comes in.

## The Solution!
As you might have guessed the solution will be Cloudinary

**What is Cloudinary?**
Cloudinary is a platform that allows you to quickly and easily create, manage and deliver digital experiences across any browser, device, and bandwidth.

## How to use Cloudinary?
**Setup**
The first thing you’ll need to do is go to the Cloudinary website and sign-up for a free account. You can find the git repository for the iOS SDK here. To integrate Cloudinary into your app you can use:

_CocoaPods:_
```
pod 'Cloudinary', '~> 3.0'
```

_Carthage:_
```
github "cloudinary/cloudinary_ios" ~> 3.0
```

_Swift package manager:_
```
https://github.com/cloudinary/cloudinary_ios.git
```

**Configuration**
Once the package is integrated, we’ll need to set up our Cloudinary object.
Your API-Key and Cloud-Name will appear in the dashboard where you created your account.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02muxtt06nej6dgm7n2l.png)

```
//Create the configuration object
let config = CLDConfiguration(cloudName: "CLOUD_NAME", apiKey: "API_KEY")
//Next we create the Cloudinary object
let cloudinary = CLDCloudinary(configuration: config)
view raw
```

Once we have our Cloudinary object set and ready to use, this is where the **MAGIC** starts.

**Upload your assets**
There are multiple ways to upload an asset to your cloud, via the API or the UI
UI — it’s as simple as dragging and dropping into your cloud.
API — You can upload through the code:

```
let request = cloudinary
.createUploader()
.upload(url: file, uploadPreset: "sample_preset", params: CLDUploadRequestParams())
.response({
    (response, error) in
    // Handle response
})
```

The only thing we’re missing here is the upload preset. An upload preset is a field we need to set through the UI. You can do this by going to the Cloudinary [website](https://cloudinary.com/), signing in, and clicking the settings icon at the top right. Click the upload option, scroll down and add a new upload preset, There are many options to customize an upload preset but I’m not going to dive into them in this blog. Check out the [Cloudinary Academy](https://training.cloudinary.com/) to learn more about what’s possible with Cloudinary’s APIs.

Once the upload preset is created, be sure to put its name in the upload preset field in the uploadfunction. Yes, it’s as simple as that to upload an asset to your cloud, once the image is there we can start using transformations!
Transformations are manipulations we can perform on an asset (image, video, etc…) there are many transformations and if you want to learn more than the examples I show here I suggest visiting Cloudinary’s [documentation](https://cloudinary.com/documentation/image_transformations).

**Transformations**
At the start of this article, I presented the problem where we have one asset, but we need it in many different sizes and aspect ratios. Let’s see how we can achieve that very easily using Cloudinary’s transformations: (I’m going to use an asset called sample)

The original image:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5k1c8jpa9l9ae8hi0c6v.png)

**Crop**
We want to create a thumbnail(250x250) for our main screen:
```
let url = cloudinary.createUrl().setTransformation(
  CLDTransformation().setWidth(250).setHeight(250).setCrop(.crop))
.generate("sample")
```

Let me explain the code line above. We’re using the cloudinary object we created before, we call the createUrl() function and set a new transformation where we give all the parameters we want to modify in the image. Lastly, we call generate with the asset name (sample).
This line of code will produce the following [URL](https://res.cloudinary.com/test123/image/upload/c_crop,h_250,w_250/sample):

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orw1yei2q0d60waqb1jc.png)

As we can see we got the 250x250 thumbnail we wanted, but the result could be improved. The “bee” which is the most interesting object in the image is cut off. What can we do? OH! Cloudinary has a few more tricks up its sleeve! Another COOL feature we can use “gravity” where we can ask Cloudinary to focus on the most interesting object in the image.

**Gravity**
```
let url = cloudinary.createUrl().setTransformation(
  CLDTransformation().setWidth(250).setHeight(250).setCrop(.crop).setGravity(.auto))
.generate("sample")
```
The output [URL](https://res.cloudinary.com/test123/image/upload/c_crop,h_250,w_250,g_auto/sample):

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srdc6604urfnmfc5qpmg.png)

And as we can see the result is much better. The focus is on the bee.

**Quality**
Let’s try another scenario. We have a 2k image, which is quite a large file, and we don't need it in its best form when we’re presenting it on the device. Roaming can’t always handle big bandwidth. To make the image lighter we can use the Cloudinary “quality” feature.

Here’s the original image (it weighs 5MB which is quite a large file)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lwp9plejt5fza7iyfxsc.png)

With Cloudinary we can do the following:
```
let url = cloudinary.createUrl().setTransformation(
  CLDTransformation().setQuality(.auto()))
.generate("big_image_sample")
```
This code will produce the following [URL](https://res.cloudinary.com/db0edm7to/image/upload/q_auto/big_image_sample):

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bemrczusuqnjyokly866.png)


And it weighs 626.56 KB. We reduced the size by a lot, and it’ll be easier to get this image on a mobile device.

## To sum up!
As we saw in the blog, Cloudinary can answer the requirement to handle the same asset in many sizes and qualities. Not only that it has many other features! I encourage you to visit the [documentation](https://cloudinary.com/documentation/) website to get the best out of the platform.

The Cloudinary SDK can also be found on [Android](https://github.com/cloudinary/cloudinary_android) and 14 more languages you can find at [Cloudinary’s git](https://github.com/cloudinary).