fbpx
How to Upload Image to Imgur in iOS using Swift

How to Upload Image to Imgur in iOS using Swift

Today, I will show you how to upload an image anonymously from your phone’s Photo Library to imgur.com

On my demo app, at the end of this article, the user first chooses an image from the Photos app and then uploads it to imgur.com.

This tutorial only focuses on how to upload an image to imgur, not selecting an image from the Photo app.

As an example, we are going to upload the following image I found on the Internet ūüź∂

Getting the Client ID

As I said before, we’re going to upload an image anonymously, but imgur still wants to know from which app they’re coming from.

For that, we need to get a Client ID from their website.

Go to https://api.imgur.com/oauth2/addclient and create an imgur account, if you haven’t already.

Fill the required fields and press submit

Copy the Client ID somewhere. We’re gonna need it later.

Imgur has some limitations on how many uploads can get from a single app every day (approx. 1,250 uploads per day). You can read more about that here.

Creating the Image Uploader

Create a method uploadImageToImgur that takes an UIImage as a parameter.

func uploadImageToImgur(image: UIImage) {
    // ...
}

Convert the image (UIImage) to Base64 text.

func uploadImageToImgur(image: UIImage) {
        getBase64Image(image: image) { base64Image in
            // ...
        }
    }

    func getBase64Image(image: UIImage, complete: @escaping (String?) -> ()) {
        DispatchQueue.main.async {
            let imageData = image.pngData()
            let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
            complete(base64Image)
        }
    }

Do an HTTP POST request, using URLSession, that takes as HTTP Header the Client ID we got before.

The form of the HTTP request is multipart/form-data.

So you need to pass the converted Base64 image into the HTTP body of the request.

let CLIENT_ID = "MY_CLIENT_ID"


func uploadImageToImgur(image: UIImage) {
        getBase64Image(image: image) { base64Image in
            let boundary = "Boundary-\(UUID().uuidString)"

            var request = URLRequest(url: URL(string: "https://api.imgur.com/3/image")!)
            request.addValue("Client-ID \(self.CLIENT_ID)", forHTTPHeaderField: "Authorization")
            request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

            request.httpMethod = "POST"

            var body = ""
            body += "--\(boundary)\r\n"
            body += "Content-Disposition:form-data; name=\"image\""
            body += "\r\n\r\n\(base64Image ?? "")\r\n"
            body += "--\(boundary)--\r\n"
            let postData = body.data(using: .utf8)

            request.httpBody = postData

            // ...
        }
    }

This is how the JSON data looks like as a result after uploading successfully your image:

{
   "data":{
      "id":"EBJIeoZ",
      "title":null,
      "description":null,
      "datetime":1582389917,
      "type":"image/jpeg",
      "animated":false,
      "width":1667,
      "height":2048,
      "size":172036,
      "views":0,
      "bandwidth":0,
      "vote":null,
      "favorite":false,
      "nsfw":null,
      "section":null,
      "account_url":null,
      "account_id":0,
      "is_ad":false,
      "in_most_viral":false,
      "has_sound":false,
      "tags":[

      ],
      "ad_type":0,
      "ad_url":"",
      "edited":"0",
      "in_gallery":false,
      "deletehash":"aCbT2JmYe6JYJp1",
      "name":"",
      "link":"https://i.imgur.com/EBJIeoZ.jpg"
   },
   "success":true,
   "status":200
}

Parse the JSON data and get the link.

func uploadImageToImgur(image: UIImage) {
        getBase64Image(image: image) { base64Image in
            
            // ...
            
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let error = error {
                    print("failed with error: \(error)")
                    return
                }
                guard let response = response as? HTTPURLResponse,
                    (200...299).contains(response.statusCode) else {
                    print("server error")
                    return
                }
                if let mimeType = response.mimeType, mimeType == "application/json", let data = data, let dataString = String(data: data, encoding: .utf8) {
                    print("imgur upload results: \(dataString)")

                    let parsedResult: [String: AnyObject]
                    do {
                        parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject]
                        if let dataJson = parsedResult["data"] as? [String: Any] {
                            print("Link is : \(dataJson["link"] as? String ?? "Link not found")")
                        }
                    } catch {
                        // Display an error
                    }
                }
            }.resume()
        }
    }

Using the Image Uploader

In your ViewController swift file, use the method we made before by calling the uploadImageToImgur and passing the image (UIImage) you want to upload.

@IBAction func uploadImageButtonAction(_ sender: UIButton) {
    uploadImageToImgur(image: selectedImage)
}
You can find the final project here

If you have any questions, please feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments