iOS
Real-time image resizing, automatic optimization, and file uploading in Android using ImageKit.io.
This is a quick start guide to show you how to integrate ImageKit in an iOS application. The code samples covered here are hosted on Github: https://github.com/imagekit-samples/quickstart/tree/master/ios.
This guide walks you through the following topics: ‌

Clone and run the tutorial app

For this tutorial, it is recommended to use the sample iOS app, as shown below. If you already have an existing iOS app, it is also possible to use that, which will be explained in the continuation of the sample app.
1
git clone
2
https://github.com/imagekit-samples/quickstart.git
Copied!
Navigate to the cloned repository, and install the dependencies that are needed to run the iOS app:
1
cd quickstart/ios/
2
pod install
Copied!
If you do not have CocoaPods Installed on your Mac, you can learn about setting up the development environment here https://guides.cocoapods.org/using/getting-started.html.
Once the dependencies have been installed, run the following command to open the Xcode Workspace:
1
open ImagekitDemo.xcodeworkspace
Copied!
Select the emulator from the dropdown. Then run the app by clicking on the Run button or by pressing ⌘ + R
You should see the following screen. This means the sample app has been set up correctly.

Setup ImageKit iOS SDK

We will be installing ImageKit iOS SDK using CocoaPods.

Initialising CocoaPods in your iOS Project

If you are not using CocoaPods in your project, you might need to add it to your project by either running pod init or adding PodFile (see example) in the root directory of your project.

Installing the SDK

To Install the SDK, add the following to the PodFile.
1
# Required to enable the use for Dynamic Libraries
2
use_frameworks!
3
4
target 'target_name' do
5
...
6
# Add to your project target
7
pod 'ImageKitIO', '~> 2.0.0'
8
...
9
end
Copied!

Initializing the SDK

Open AppDelegate.swift file, this is where we will initialize our SDK with the following parameters.
1
ImageKit.init(
2
publicKey: "your_public_api_key=",
3
urlEndpoint: "https://ik.imagekit.io/your_imagekit_id",
4
transformationPosition: TransformationPosition.PATH,
5
authenticationEndpoint: "http://www.yourserver.com/auth"
6
)
Copied!

Rendering Images in iOS application

Image URL can be created from an image path or using the absolute image URL. You can learn more about it in docs.
To render an image using an absolute URL (full image URL), we can instantiate the ImageKitURLConstructor
1
let urlConstructor = ImageKit.shared.url(
2
src: "https://ik.imagekit.io/demo/default-image.jpg"
3
)
Copied!
To create a URL from the image path, we can instantiate the ImageKitURLConstructor which takes the URL endpoint, image path, and transformation position as parameters to create the transformed url.
1
let urlConstructor = ImageKit.shared.url(
2
urlEndpoint: "https://ik.imagekit.io/demo"
3
path: "default-image.jpg",
4
transformationPosition: TransformationPosition.QUERY
5
)
Copied!
The transformation position (path or query) is only valid when creating a URL from the image path. Transformations are always added as query parameters if the URL is created from an absolute image path using src.
The iOS SDK provides a function for each transformation parameter, making the code simpler and readable. To add transformations, the functions can be chained with urlConstructor.
1
urlConstructor = urlConstructor.height(height: 400)
2
urlConstructor = urlConstructor.aspectRatio(width: 3, height: 2)
Copied!
Finally, once all the required transformations are defined, call create function to get the final transformed URL
1
let url = urlConstructor.create()
2
// https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-400,ar-3-2
Copied!
It will look as shown below. In the sample app, the buttons are present to demonstrate the use of different transformations.

Common image manipulation in iOS application

This section covers the basics:‌
    ​Basic image resizing
    Crop Mode
    ​Aspect Ratio
    ​Chained transformation
ImageKit iOS SDK provides a function to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. See the full list of supported transformations in iOS SDK on Github.
The complete list of transformations supported and their usage in ImageKit can be found here. If a transformation is supported in ImageKit, but if a name for it cannot be found in the SDK, then use the addCustomTransformation function and pass the transformation code from ImageKit docs as the first parameter and value as the second parameter. For example - .addCustomTransformation("w", "400").

Basic image resizing

Let's resize the image to a height of 150 and a width of 150.
1
urlConstructor = urlConstructor.height(height: 150)
2
urlConstructor = urlConstructor.height(height: 400)
3
let url = urlConstructor.create()
Copied!
Output:

Crop mode

Let’s now see how different crop mode works. We will try the pad_resize crop strategy. In this strategy, the output image's dimension (height and width) is the same as requested, no cropping occurs, and the aspect ratio is preserved. This is accomplished by adding padding around the output image to get it to match the exact dimension as requested. You can read more about this here.
1
urlConstructor = urlConstructor.width(width: 300)
2
urlConstructor = urlConstructor.height(height: 200)
3
urlConstructor = urlConstructor.cropMode(cropMode: CropMode.PAD_RESIZE)
4
let url = urlConstructor.create()
Copied!
Output:

Aspect ratio

You can use the ar parameter to change the aspect ratio like this:
1
urlConstructor = urlConstructor.height(height: 400)
2
urlConstructor = urlConstructor.aspectRatio(width: 3, height: 2)
3
let url = urlConstructor.create()
Copied!
Output:

Chained transformation

Chained transformations provide a simple way to control the sequence in which transformations are applied.
Let’s try it out by resizing an image, then rotating it:
1
urlConstructor = urlConstructor.height(height: 400)
2
urlConstructor = urlConstructor.width(width: 300)
3
urlConstructor = urlConstructor.chainTransformation()
4
urlConstructor = urlConstructor.rotation(rotation: Rotation.VALUE_90)
5
let url = urlConstructor.create()
Copied!
Output:

Adding an overlay to images in iOS application

ImageKit.io allows you to add text and image overlay dynamically.

Text overlay

Text overlay can be used to superimpose text on an image. Try it like so:
1
urlConstructor = urlConstructor.width(width: "400")
2
urlConstructor = urlConstructor.overlayText(overlayText: "Hand with a green plant")
3
urlConstructor = urlConstructor.overlayTextColor(overlayTextColor: "264120")
4
urlConstructor = urlConstructor.overlayTextFontSize(overlayTextSize: 30)
5
urlConstructor = urlConstructor.overlayX(overlayX: 10)
6
urlConstructor = urlConstructor.overlayY(overlayY: 20)
7
let url = urlConstructor.create()
Copied!
Output:

Image overlay

Image overlay can be used like this:
1
urlConstructor = urlConstructor.overlayImage(overlayImage: "logo-white_SJwqB4Nfe.png")
2
urlConstructor = urlConstructor.overlayX(overlayX: 10)
3
urlConstructor = urlConstructor.overlayY(overlayY: 20)
4
let url = urlConstructor.create()
Copied!
Output:

Client-side file uploading

Let's learn how to upload an image to our media library.
iOS SDK provides ImageKitUploader which provide functions to allow upload files to the ImageKit media library directly from the client-side.
For using upload functionality, we need to pass publicKey and authenticationEndpoint while initializing the SDK. Replace your_url_endpoint , your_public_key, your_authentication_endpoint with actual values.
1
ImageKit.init(
2
publicKey: "your_public_api_key",
3
urlEndpoint: "your_url_endpoint",
4
transformationPosition: TransformationPosition.PATH,
5
authenticationEndpoint: "your_authentication_endpoint"
6
)
Copied!
For this, we would need a dummy backend app to authenticate our upload request. API authentication for upload always happens on the backend for security reasons.
The tutorial repository comes with a sample backend server that we can use.

Setting up the backend app

For this quick start guide, we have provided the sample implementation of the authentication endpoint in using the ImageKit Node.js SDK and Express.
In a new terminal window, navigate to the Server folder inside the tutorial project and install its npm packages:
1
cd Server/
2
npm install
Copied!
Let's modify index.js to implement http://localhost:8080/auth which is our authenticationEndpoint .
1
/*
2
This is our backend server.
3
Replace your_url_endpoint, your_public_key, your_private_key
4
with actual values
5
*/
6
const express = require('express');
7
const app = express();
8
9
var cors = require('cors');
10
app.use(cors());
11
12
const ImageKit = require('imagekit');
13
const imagekit = new ImageKit({
14
privateKey: "your_private_key",
15
publicKey: "your_public_key",
16
urlEndpoint: "your_url_endpoint"
17
})
18
19
app.get("/auth", function (req, res) {
20
var signature = imagekit.getAuthenticationParameters();
21
res.status(200);
22
res.send(signature);
23
});
24
25
app.listen(8080, function () {
26
console.log("Live at Port 8080");
27
});
Copied!
Finally, run the backend app.
1
node index.js
Copied!
You should see a log line saying that the app is “Live on port 8080”.
If you run curl http://localhost:8080/auth in the terminal, you should see a JSON response like this. Actual values will vary.
1
{
2
token: "5dd0e211-8d67-452e-9acd-954c0bd53a1f",
3
expire: 1601047259,
4
signature: "dcb8e72e2b6e98186ec56c62c9e62886f40eaa96"
5
}
Copied!
Configure the auth endpoint in the frontend app
Head over to AppDelegate.swift and ensure the authenticationEndpoint is set to http://localhost:8080/auth

Upload a file

To upload an image to the media library, the ImageKit iOS SDK provides ImageKitUploader . For complete API reference for the image upload function, check out the docs on the ImageKit iOS Git Repository.
The ImageKit.shared.uploader().upload function can ingest files through UIImage, NSData or Url of a remote image
1
ImageKit.shared.uploader().upload(
2
file: image,
3
fileName: "sample-image.jpg",
4
useUniqueFilename: true,
5
tags: ["demo"],
6
folder: "/",
7
isPrivateFile: false,
8
customCoordinates: "",
9
responseFields: "",
10
progress: { progress in
11
// Handle Progress
12
},
13
completion: { result in
14
switch result{
15
case .success(let uploadAPIResponse):
16
// Handle Success Response
17
case .failure(let error as UploadAPIError):
18
// Handle Upload Error
19
case .failure(let error):
20
// Handle Other Errors
21
}
22
}
23
)
Copied!
After a successful upload, you should see the newly uploaded file in the Media Library of your ImageKit dashboard.
If you don't see the file, check if there are any errors in the error log. Make sure that the private API key has been configured. The server app is running. And the uploaded file type is supported by ImageKit.

What's next

The possibilities for image manipulation and optimization with ImageKit are endless. Learn more about it here:
Last modified 10mo ago