I want to grab the ImagePath from the response.
Response look like this
The response for print(response.result.value)
I am using Alamofire POST request to get the data from Api. Here is my code:
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
}
let Response = response.result.value
print("Response JSON:- \(String(describing: Response))")
let mydata = (String(describing : Response))
let jSon = JSON(mydata)
print("New :- \(String(describing: jSon["data"]["ImagePath"].stringValue))")
print("New :- \(jSon["data"]["ImagePath"])")
print(jSon["data"]["ImagePath"])
print(jSon["status"].stringValue)
if let data = response.result.value {
let json = JSON(data)
//print(json)
}
}
Try optional handling this way
if let Response = response.result.value as? [String : Any],
myData = Response["data"] as? [String : Any],
imgPath = myData["ImagePath"] {
print("ImagePath --> ", imgPath)
}
Related
I am trying to upload image to server, but my code sometimes uploads the image and sometimes don't and gives a Status = 400 and says failed to upload file. Can you guys check that out why my code give me this error. And i note it gives me this error sometimes.
Here is the postman requirements:Postman Image.And here is the Status = 400 response:
Response.
Here is my code:
func UPLOD(){
let image = myImageView.image
let serviceName = "http://192.168.80.21:8800/api/v1/upload/uploadfile"
var parameters = [String: Any]()
parameters["Folder"] = "uploadfile"
parameters["Filename"] = "demo3\(self.currentTimeStamp)"
parameters["Ext"] = "jpeg"
parameters["FileToUpload"] = image?.jpegData(compressionQuality: 0.5)
guard let token = UserDefaults.standard.string(forKey: "accesstoken") else {
return
}
print("Create button ACCESS KEY::::- \(token)")
let headers: HTTPHeaders = [
"x-access-token": token,
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters {
if key == "FileToUpload" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "demo3\(self.currentTimeStamp)",
mimeType: "image/jpeg"
//_img.jpg
)
} else {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}}},
to: serviceName, method: .post, headers: headers) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response.result.value!)
}
upload.responseJSON { [self] response in
if let Response = response.result.value as? [String : Any],
let myData = Response["data"] as? [String : Any],
let imgPath = myData["status"] {
imageUrl = imgPath as! String
print(imageUrl)
print("ImagePath --> ", imgPath)
responseURL = imageUrl
let defaults = UserDefaults.standard
defaults.setValue(imageUrl, forKey: "imageURL")
let key = defaults.object(forKey: "imageURL")
print(key as Any)
self.alamofireRequest(requestURL: "http://192.168.80.21:3204/api/product/create")
}
if let data = response.result.value {
let _ = JSON(data)
}
}
break
case .failure(let encodingError):
print(encodingError)
break
}
}
}
I am trying to upload image to server with folder name, filename and extension as parameter. I have done some code, but it gives me a Nil response. can someone help me to solve that?
Sometimes this uploads image and sometimes don't. And when it failed to upload image gives a Nil response.and sends some garbage value to server.
Here is my image upload method:
func UPLOD(){
let image = myImageView.image!
let serviceName = "http://192.168.80.21:8800/api/v1/upload/uploadfile"
var parameters = [String: AnyObject]()
parameters["Folder"] = "uploadfile" as AnyObject?
parameters["Filename"] = "demo\(self.currentTimeStamp)" as AnyObject?
parameters["Ext"] = "jpg" as AnyObject?
parameters["FileToUpload"] = image.jpegData(compressionQuality: 0.5) as AnyObject?
guard let token = UserDefaults.standard.string(forKey: "accesstoken") else {
return
}
print("Create button ACCESS KEY::::- \(token)")
let headers: HTTPHeaders = [
"x-access-token": token
]
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters {
if key == "FileToUpload" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "demo\(self.currentTimeStamp)",
mimeType: "image/jpg"
//_img.jpg
)
} else {
//Data other than image
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}}},
to: serviceName, method: .post, headers: headers) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
//print response.result
print(response.result.value as Any)
}
upload.responseJSON { [self] response in
if let Response = response.result.value as? [String : Any],
let myData = Response["data"] as? [String : Any],
let imgPath = myData["ImagePath"] {
imageUrl = imgPath as! String
print(imageUrl)
print("ImagePath --> ", imgPath)
responseURL = imageUrl
let defaults = UserDefaults.standard
defaults.setValue(imageUrl, forKey: "imageURL")
let key = defaults.object(forKey: "imageURL")
print(key as Any)
self.alamofireRequest(requestURL: "http://192.168.80.21:3204/api/product/create")
}
if let data = response.result.value {
let _ = JSON(data)
}
}
break
case .failure(let encodingError):
print(encodingError)
break
}
}
}
Swift 5.0
pod 'Alamofire', '~> 5.4'
func postImageData(url:String, param:[String:Any], img:Data) {
print("POST URL : ", url)
let header: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(img, withName: "image", fileName: "image", mimeType: "image/jpeg")
for (key,value) in param {
MultipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}, to: url, method: .post, headers: header).uploadProgress { (progress) in
print(progress.fractionCompleted)
} .responseJSON { response in
switch response.result {
case .success:
if let JSON = response.value as? [String: Any] {
let flag = JSON["flag"] as! Bool
let code = JSON["code"] as! Int
} else {
}
break
case .failure(let error):
if let data = response.data {
print("Response Error Line No. 265:- \(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)")
}
break
}
}
}
I want to upload image using Multipart/formdata put request in iOS Swift using Almofire Networking which has few parameters and one parameter contains JSON. e.g
"parameter_name":{
"field_1" : {
"type" : "MULTISELECT",
"value" : [
"Option 1",
"Option 3"
],
"name" : "Multi Selection"
},
"field_2" : {
"type" : "DATE",
"name" : "BirthDate",
"value" : "2000-09-08"
},
"field_3" : {
"type" : "SINGLESELECT",
"value" : "Option1",
"name" : "Single Select"
}
}
This is one parameter in multipart formdata with other parameters like name, email, photo and more (all are of type string)
Could anyone help me achieving this as using Swift & AlamoFire As I am receiving 503 status code for this.
Note:- In postman same API is working fine.
What I have done so far is:
Alamofire.upload(multipartFormData: { multipartData in
parameters.forEach { (key, value) in
if let arrdata = (value as? [AnyHashable : Any]) {
if arrdata.count > 0 {
let arrdatas = try! JSONSerialization.data(withJSONObject: arrdata, options: [])
multipartData.append(arrdatas, withName: key as String)
}
}
guard
let data = (value as? String)?
.data(using: .utf8)
else { return }
multipartData.append(data, withName: key)
}
if let img = photo,
let data = UIImageJPEGRepresentation(img, 0.0) {
multipartData
.append(data,
withName: Keys.photo,
fileName: Keys.fileName,
mimeType: Keys.mimeType)
}
},
to: "My URL",
headers: requestType.headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseData(completionHandler: { response in
if let statusCode = response.response?.statusCode,
200 <= statusCode && statusCode < 300,
let data = response.data {
guard
let decoded = try? JSONSerialization.jsonObject(with: data, options: []),
let dic = decoded as? [String: Any] else {
return
}
printOnlyOnDebug("Response got is --> \(self.convertToJSON(toConvert: dic))")
success(data)
} else {
guard
let data = response.data,
let decoded = try? JSONSerialization.jsonObject(with: data, options: []),
let dic = decoded as? [String: Any],
let message = dic[Keys.message] as? String else {
let code = response.response?.statusCode == 503 ? 401 : response.response?.statusCode
failure(code, "Network error")
return
}
failure(response.response?.statusCode, message)
}
})
case .failure(let error):
failure(nil, error.localizedDescription)
}
})
Also header contains 'Content-Type' as 'multipart/form-data'
I forgot to mention method type PUT in AlamoFire request so it was creating POST request and it was causing the issue.
Alamofire.upload(multipartFormData: { multipartData in
parameters.forEach { (key, value) in
if let arrdata = (value as? [AnyHashable : Any]) {
if arrdata.count > 0 {
let arrdatas = try! JSONSerialization.data(withJSONObject: arrdata, options: [])
multipartData.append(arrdatas, withName: key as String)
}
}
guard
let data = (value as? String)?
.data(using: .utf8)
else { return }
multipartData.append(data, withName: key)
}
if let img = photo,
let data = UIImageJPEGRepresentation(img, 0.0) {
multipartData
.append(data,
withName: Keys.photo,
fileName: Keys.fileName,
mimeType: Keys.mimeType)
}
},
to: "My URL",
method:.put,
headers: requestType.headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseData(completionHandler: { response in
if let statusCode = response.response?.statusCode,
200 <= statusCode && statusCode < 300,
let data = response.data {
guard
let decoded = try? JSONSerialization.jsonObject(with: data, options: []),
let dic = decoded as? [String: Any] else {
return
}
printOnlyOnDebug("Response got is --> \(self.convertToJSON(toConvert: dic))")
success(data)
} else {
guard
let data = response.data,
let decoded = try? JSONSerialization.jsonObject(with: data, options: []),
let dic = decoded as? [String: Any],
let message = dic[Keys.message] as? String else {
let code = response.response?.statusCode == 503 ? 401 : response.response?.statusCode
failure(code, "Network error")
return
}
failure(response.response?.statusCode, message)
}
})
case .failure(let error):
failure(nil, error.localizedDescription)
}
})
I have the URL to display the data and it is working in the urlsession. But I need Alamofire so I have done it in the Alamofire. But in that it is showing as:
Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(404)
How to fix the problem?
This is the code in the Alamofire:
Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON{ response in
let status = response.response?.statusCode
print("STATUS \(status)")
print(response)
switch response.result {
case .success(let data):
print("success",data)
let result = response.result
print(result)
if let wholedata = result.value as? [String:Any]{
print(wholedata)
if let data = wholedata["data"] as? Array<[String:Any]>{
print(data)
print(response)
for question in data {
let typebutton = question["button_type"] as? String
print(typebutton)
self.type = typebutton
let options = question["options"] as! [String]
// self.dataListArray1 = [options]
self.tableArray.append(options)
// self.savedataforoptions(completion: <#T##(NH_OptionslistDataSourceModel?) -> ()#>)
self.no = options.count
}
print(self.tableArray)
let newDataSource:QuestionDataSourceModel = QuestionDataSourceModel(array: data)
completion(newDataSource)
}
}
case .failure(let encodingError ):
print(encodingError)
// if response.response?.statusCode == 404{
print(encodingError.localizedDescription)
completion(nil)
}
}
}
I got data from API in this format but the problem is that I want to get all questions and answers from the API but whenever I try to get the value by using the key value it returns nil value and application crashes
this is my api data looks like after getting into a dictionary
here's my code for getting data from API
Alamofire.request(url, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: header ).responseJSON {
response in
switch response.result {
case .success:
print(response)
if let result = response.result.value {
print(result)
let responseDict = result as! [String : Any]
print(responseDict)
let data = responseDict["Result"] as! [Any]
print(data)
}
break
case .failure(let error):
print(error)
}
}
You can try
if let res = responseDict["Result"] as? [[String:Any]] {
for item in res {
if let ques = item["Question"] as? String {
print(ques)
}
if let op = item["Options"] as? [[String:Any]] {
print(op)
}
}
}