Search code examples
iosswift3uploadalamofireimgur

Getting image URL after uploading to Imgur API using Swift 3


I am uploading images anonymously using the Imgur API and Alamofire. However, I am not getting the url in the response json. Here is my code:

    static func post(image: UIImage, for username: String) {

    let imageData = UIImagePNGRepresentation(image)
    let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)

    let url = "https://api.imgur.com/3/upload"

    let parameters = [
        "image": base64Image
    ]

    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image, 1) {
            multipartFormData.append(imageData, withName: username, fileName: "\(username).png", mimeType: "image/png")
        }

        for (key, value) in parameters {
            multipartFormData.append((value?.data(using: .utf8))!, withName: key)
        }}, to: url, method: .post, headers: ["Authorization": "Client-ID " + Constants.IMGUR_CLIENT_ID],
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.response { response in
                        print(response) // url nowhere to be found
                    }
                case .failure(let encodingError):
                    print("error:\(encodingError)")
                }
    })

}

Here is the printed response:

enter image description here


Solution

  • The issue in your code is that you are just printing the response of the request, you actually need to parse that into JSON and than check the response of your request, it does contain the image url you just uploaded. This is how you should parse the response and get the image url.

    static func post(image: UIImage, for username: String) {
    
        let imageData = UIImagePNGRepresentation(image)
        let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
    
        let url = "https://api.imgur.com/3/upload"
    
        let parameters = [
            "image": base64Image
        ]
    
        Alamofire.upload(multipartFormData: { multipartFormData in
            if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: username, fileName: "\(username).png", mimeType: "image/png")
            }
    
            for (key, value) in parameters {
                multipartFormData.append((value?.data(using: .utf8))!, withName: key)
            }}, to: url, method: .post, headers: ["Authorization": "Client-ID " + Constants.IMGUR_CLIENT_ID],
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.response { response in
                            //This is what you have been missing
                             let json = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as! [String:Any]
                             print(json)
                             let imageDic = json?["data"] as? [String:Any]
                             print(imageDic?["link"])
                        }
                    case .failure(let encodingError):
                        print("error:\(encodingError)")
                    }
        })
    
    }