Handling base64String as response in Swift

Viewed 543
  • I am receiving a base64String for Image in response of an Api but unable to get the result through Alamofire.request method (tried with get as well as post).

     Alamofire.request(ApiUrl, method: .get, parameters: [:] , encoding:JSONEncoding.default, headers:kAuthorizationHeader).responseString { (response) in
        switch response.result {
        case .success(let responseString):
            if let imageData = Data(base64Encoded: responseString),
                let image = UIImage(data: imageData) {
                print("image")
            }
        case .failure(let error):
            print("\(error.localizedDescription)")
        }
    }
    
  • It always returns a failure with 'requestTimeOut' in case of get method and 'Invalid value around character 0' for post.

    Is there any way through which we can get the base64String so that I can convert the same to UIImage? Please advise.

1 Answers

I went and created a view in my python project which responds a string in a url. So using alamofire.. you need to request string rather than responseJSON

Alamofire.request("http://127.0.0.1:8000/stringResponse/", method: .get).responseString { (response) in
         switch response.result {
        case .success(let responseString):
            if let imageData = Data(base64Encoded: responseString),
                let image = UIImage(data: imageData) {
                print("image")
            }
        case .failure(let error):
            print("\(error.localizedDescription)")
        }
    }
Related