Handling base64String as response in Swift - ios

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.

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

upload image to server in iOS swift

I'm new in swift.
I have no idea about how to upload image from UIImage Piker Controller to server using Alamofire. I tried many solution from stackOverflow And Google etc from last week unfortunately. But I can't figure out it.
Please anyone Help me.
Now I tried to implement this code:
func uploadImgRiderAPI(){
print("I am in uploadImgAPI")
let imgData = UIImageJPEGRepresentation(profilePicOut.image!, 0.2)! //Error: UIImageJPEGRepresentation' has been replaced by instance method 'UIImage.jpegData(compressionQuality:)'
let parameters : [String : Any] = ["image": imgData, "riderId" : "5ed4eecfe3ec0c6b7c8e4990"]
guard let url = URL(string: "\(Constents.baseURL)/rider/uploadImage") else {
print("Invalid URL")
return
}
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "image",fileName: "alkaram.png", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8), withName: key) // Error: Cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members
}
}, to:url) { (result) in
switch result {
case .success(let upload, _, _): //Error : Pattern cannot match values of type 'URLRequest'
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
if let result = response.data {
do {
let jsonData = try JSONEncoder().encode(parameters)
let jsonString = String(data: jsonData, encoding: .utf8)
let url = URL(string: self.retrivedRiderProfileImg!)
print("Complete URL is :-> \(url)")
let placeholderImage = UIImage(named: "referral_icon")!
self.profilePicOut.af_setImage(withURL: url!, placeholderImage: placeholderImage)
print("JSON String : " + jsonString!)
print("And Responce is : \(response)")
} catch {
print(error)
}
}
}
case .failure(let encodingError): //Error : Pattern cannot match values of type 'URLRequest'
print(encodingError)
}
}
}
Firstly, You need to replace the old API for UIImageJPEGRepresentation with the new jpegData(compressionQuality:) method.
Replace this:
let imgData = UIImageJPEGRepresentation(profilePicOut.image!, 0.2)!
With this:
guard let imgData = profilePicOut.image?.jpegData(compressionQuality: 0.2) else { return }
And replace the case where only one parameter for URLRequest is returned to accept just one parameter as the error states.
Replace this:
case .success(let upload, _, _):
With this:
case .success(let upload):

Polyline in google map for IOS swift

I have been working in google poly line functionality. I have initialised the URL and I have used alamofire request. Everything with the URL is working fine but I could not draw the line and it was stating like invalid URL.
I have attached the code which I have tried.
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(pickupcordinates)&destination=\(dropCoordinates)&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270"
Alamofire.request(urlString,method: .get, parameters: nil,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
invalidURL(url: "https://maps.googleapis.com/maps/api/directions/json?origin=13.03589205752495,80.25411217280107&destination=13.0277895999, 80.22673778239999&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270")
The above is my console response error
I want to draw a poly line from my source to destination.
I am using this way give it a try. May help you.
func drawPath(source: CLLocationCoordinate2D, destination: CLLocationCoordinate2D){
let orgin = "\(source.latitude),\(source.longitude)"
let destin = "\(destination.latitude),\(destination.longitude)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(orgin)&destination=\(destin)&mode=driving"
Alamofire.request(url).responseJSON { response in
switch response.result {
case .success:
let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue
print(response)
break
case .failure(let error):
print(error)
}
}
}

errors decoding json with Alamofire

I try to decode JSON data from web using Alamofire. My app is sending the same GET requests, which differs by id. Some JSON is decoded successfully, but some can not be decoded. What can be the problem? How can I solve this issue? All responses are checked by JSON validator and are valid. Trying to decode with URLSession.shared.dataTask(with: url) just cannot decode a single response, even response that was successfully decoded with Alamofire
Code is:
var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/"
hostURL = hostURL + declarationID
print(hostURL)
Alamofire.request(hostURL).responseData { response in
switch response.result {
case .success(let data):
let declarationInfoElement = try? JSONDecoder().decode(DeclarationInfoElement.self, from: data)
print(declarationInfoElement)
case .failure:
print("fail")
}
}
Console output is:
https://public-api.nazk.gov.ua/v1/declaration/3509369f-b751-444a-be38-dfa66bb8728f
https://public-api.nazk.gov.ua/v1/declaration/3e7ad106-2053-48e4-a5d2-a65a9af313be
https://public-api.nazk.gov.ua/v1/declaration/743b61d5-5082-409f-baa0-9742b4cc2751
https://public-api.nazk.gov.ua/v1/declaration/5d98b3d9-8ca6-4d5d-b39f-e4de98d451aa
https://public-api.nazk.gov.ua/v1/declaration/7e3c488c-4d6a-49a3-aefb-c760f317dca4
nil
Optional(Customs_UA.DeclarationInfoElement(id: "4647cd5d-5877-4606-8e61-5ac5869b71e0")
nil
nil
nil
#objc func getJSON(){
let hostURL = "https://public-api.nazk.gov.ua/v1/declaration/"
print(hostURL)
Alamofire.request(hostURL).responseData { response in
switch response.result {
case .success(let data):
do {
if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
{
print(json)
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
print(data)
case .failure:
print("fail")
}
}
}
The problem is that some parameters of the JSON are optional. You have to post your DeclarationInfoElement class to check.
Use something like this to detect the error.
class DeclarationInfoElement: Decodable {
let id: String?
let created_date: String?
/// and so on
}

Cannot call value of non function type Data? SwiftyJSON

Tried almost every solution found here. But couldn't solve this issue.I am using Alamofire and swiftyJSON.
Code below:
upload.responseJSON(completionHandler: { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
print("Result Value: \(response.result.value.debugDescription)")
spinner.stopAnimating()
print(response.error.debugDescription)
//print("\(response.result.error)")
if response.result.isSuccess {
if let result = response.result.value {
print("JSON: \(result)") // serialized json response
let json = JSON(result)
}
}
})
Try to use this code:
switch response.result {
case .success(let value):
let json = JSON(value)
print(json)
case .failure(let error): print(error)
}
Check if this works
let json = JSON(result1)
Also there is a possibility that the result value is string. For that try this -
if let dataFromString = result1.data(using: .utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}
Let me know if any of this works for you else I will try to find out something else.

Alamofire receive and parse an array of strings swift

I getting the result as an array of strings like this
["India","America","Australia","China","Russia"]
And I'm using Alamofire to get the response using code. There's no error, but I got the result as null. Please help in parsing this.
sessionManager?.request(strURL, method: method, parameters: params, encoding: encoding , headers: headers).responseJSON { (response) in
switch response.result {
case .success:
let resJson = JSON(response.result.value!)
success(resJson)
break
case .failure(let error):
failure(error as NSError)
break
}
}
Try this:
if let responseData = response.result.value{
let responsevalue = responseData as? [String]
}
For anyone looking for another derived answer, just put this chunk of code after Alamofire.request(...):
.responseJSON(completionHandler: { (response) in
switch response.result{
case .success(let value):
// Here is your array of String
let arrayOfStrings = value as? [String]
case .failure(let error):
// Some code when error happens...
print(error.localizedDescription)
}
})
This solution using SwiftyJSON:
.responseJSON(completionHandler: { (response) in
switch response.result{
case .failure(let error):
print(error.localizedDescription)
case .success(let res):
let json = JSON(res)
let res = json["result"]
var models = [String]()
if let models1 = company["models"].array {
for model in models1 {
guard let mod = model.string else { return }
models.append(mod)
}
}
}
})

Resources