Alamofire.upload SwiftLint violation - swift

The code for uploading image with Alamofire triggers a SwiftLint violation. How can it be fixed?
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "profileImage", fileName: "image.png", mimeType: "image/jpg")
}, usingThreshold: UInt64.init(), to: requestURL, method: .post, headers: headers) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let error = response.error {
completionBlock(.failure(error as NSError))
return
}
completionBlock(.success(response))
}
case .failure(let error):
completionBlock(.failure(error as NSError))
}
}
Multiple Closures with Trailing Closure Violation: Trailing closure
syntax should not be used when passing more than one closure argument.
(multiple_closures_with_trailing_closure)

The error is telling you not to use trailing closure syntax when there is more than one closure parameter.
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "profileImage", fileName: "image.png", mimeType: "image/jpg")
}, usingThreshold: UInt64.init(), to: requestURL, method: .post, headers: headers, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let error = response.error {
completionBlock(.failure(error as NSError))
return
}
completionBlock(.success(response))
}
case .failure(let error):
completionBlock(.failure(error as NSError))
}
})

Related

Swift AlamoFire PUT request

I have a JSON file with this struct:
{
"example": {
"projects": [
{ "projectname" : "abc",
"date" : "20200930",}
{ "projectname" : "bac",
"date" : "20200803",}
]
}
}
I want to update first projectname, but not the date connected to it. But the AF.request method give me back error 400 (Invalid JSON body passed.)
let user = "username"
let password = "password"
let params = ["example":
["projects":
["projectname": "New Name"]
]
]
let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers : HTTPHeaders = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers).responseJSON { AFdata in
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: AFdata.data!) as? [String: Any] else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Could print JSON in String")
return
}
print(prettyPrintedJson)
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}
Thanks for your help!
I believe you are missing the encoder parameter in you request:
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers, encoder: JSONParameterEncoder.default).responseJSON { AFdata in
Without it Alamofire cannot know that your parameters should be encoded as JSON.

Uploading multiple images(with parameters) using multipart form data - Alamofire 5

I have been trying to upload multiple images(3) with parameters using alamofire but i cant seem to do it.(My lack of knowledge). Could someone kindly help me out with this?
This is what i have tried
{
let headers: HTTPHeaders = [
xyz
]
let param : [String: Any] = [
"emp_Id" : "",
"device_Identifier" : "",
"timestamp" : "",
"description" : "",
"handoverStatus" : ""
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imgData0, withName: "media1" , fileName: "file0.jpeg", mimeType: "image/jpeg")
multipartFormData.append(imgData1, withName: "media2",fileName: "file1.jpg", mimeType: "image/jpg")
multipartFormData.append(imgData2, withName: "media3",fileName: "file1.jpg", mimeType: "image/jpg")
// I think im supposed to add the last part here but i dunno how to do that
},
to: "http://ip.here.--.--/new.php", method: .post , headers: headers)
.response { resp in
print(resp)
}
}
This is what the server expects
[{"key":"media1","description":"","type":"file","value":["/C:/Users/x/x/Saved Pictures/x.jpg"]},
[{"key":"media2","description":"","type":"file","value":["/C:/Users/x/x/Saved Pictures/x.jpg"]},
[{"key":"media3","description":"","type":"file","value":["/C:/Users/x/x/x.jpg"]},
{"key":"model","value":"{\"emp_Id\": \"6\",\"device_Identifier\":\"Device 01\",\"timestamp\":\"\123\,
”\description\”:\”description\",”handoverStatus”:”false”}","type":"text"}]
I dunno how to add the last part to the multipart form data, could some point me in the right direction ?
Thanks
Try this method to upload multiple images
class func uploadImageWithURL(endPath : String, dictImage : [String:[UIImage]], parameter : [String : Any], header : HTTPHeaders? = nil, success : #escaping ( Any? )->Void, failure : #escaping (Error) -> Void){
let baseUrl = "your base URL"
let fullUrl = baseUrl + endPath
var headers = ["Content-type" : "multipart/form-data"]
if let header = header{
headers = header
}
let url = (try? URLRequest(url: fullUrl, method: .post, headers: headers))!
upload(multipartFormData: { (multipartData) in
for imagesData in dictImage {
for arrimage in imagesData.value{
multipartData.append(arrimage.jpegData(compressionQuality: 0.50)!, withName: imagesData.key, fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image/jpeg")
}
}
for (key, value) in parameter {
multipartData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, with: url) { (resultData) in
switch resultData{
case .success(let upload, let streamingFromDisk, let fileURL):
print("File URL : \(String(describing: fileURL))")
print("Streaming From Disk : \(streamingFromDisk)")
upload.uploadProgress(closure: { (progress) in
print("Progress : \(progress.fractionCompleted)")
})
upload.responseJSON(queue: nil, options: .allowFragments, completionHandler: { (response) in
if let value = response.result.value
{
success(value)
}
})
case .failure(let error):
failure(error)
print(error)
}
}
}

how to store the JSON format to database through api using Alamofire in swift4

{
"Employee_ID" : "160",
"Date" : "10-06-2019",
"Time" : [
{
"In" : "10:30",
"In_Location": "506/507, 1st Main RoadMurugeshpalya, Bengaluru",
"Out" : "18:30",
"Out_Location": "506/507, 1st Main RoadMurugeshpalya, Bengaluru",
"Description" : "Designing Login Page",
"Total" : "240"
}
]
}
my actual code is:
Alamofire.upload( multipartFormData: { multipartFormData in
multipartFormData.append("160".data(using: .utf8)!, withName: "Employee_ID")
multipartFormData.append(dateString.data(using: .utf8)!, withName: "Date")
multipartFormData.append(InTime.data(using: .utf8)!, withName: "In")
multipartFormData.append(self.locationName.data(using: .utf8)!, withName: "In_Location")
// for (key, value) in timeParams {
// multipartFormData.append(value.data(using: .utf8)!, withName: key)
// }
}, to: "http://touramical-test.infanion.com:5000/api/save-tempion/", method: .post, headers: nil) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { answer in
print(answer.response?.statusCode as Any)
}
upload.uploadProgress { progress in
//call progress callback here if you need it
}
case .failure(let encodingError):
print("multipart upload encodingError: \(encodingError)")
}
}
it uploads only employee Id and date but not time parameters
First, try to transform your data in a struct like this:
struct Employer: Codable {
var employeeID, date: String
var time: [Time]
enum CodingKeys: String, CodingKey {
case employeeID = "Employee_ID"
case date = "Date"
case time = "Time"
}
}
struct Time: Codable {
var timeIn, inLocation, out, outLocation: String
var timeDescription, total: String
enum CodingKeys: String, CodingKey {
case timeIn = "In"
case inLocation = "In_Location"
case out = "Out"
case outLocation = "Out_Location"
case timeDescription = "Description"
case total = "Total"
}
}
And later try to do something like this:
let jsonEncoder = JSONEncoder()
var jsonData = try? jsonEncoder.encode(yourTimeStruct) as? [String: Any]
Alamofire.request(yourURL, method: .post, parameters: jsonData, encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}

how to set multipart "withname" with dictionary in swift?

I want to send the images to the server with multipart form. Normal
image uploading is working with the multipart but facing the
problem is when I need to set withname with array inside dictionary.
alamofireManager.upload(multipartFormData: { multipartFormData in
for i in 0..<images.count {
let imgData = UIImagePNGRepresentation(images[i])!
multipartFormData.append(imgData, withName: "fileUpload",fileName: "\(images)i", mimeType: "image/png")
}
Server parameters are like
"documants" : [{
"documentType" : "Image",
"fileUpload: "" // multipart data
},{
"documentType" : "Image",
"fileUpload: "" // multipart data
}]
So how to mention the node name documents[0].fileUpload with withName using multipartFormData?
You can implement 'multipart' in this way...using Swift4.2
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
let url = try! URLRequest(url: baseURL, method: .post, headers: headers)
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(img, withName: "file", fileName: imgName, mimeType: "\(fileType ?? "jpg")")
}, with: url) { result in
switch result {
case .success(let upload, _, _):
upload.responseString { response in
switch (response.response?.statusCode)
{
case 200: //The request was fulfilled
print("Network - HandShaking Successfull...!!!")
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
Hope you will get idea of 'multipart'...!!!

Swift 3 Alamofire POST with Headers Parameters, Query Parameters, and Request Body

I am faily new to Alamofire itself, so forgive me if this is a simple one.
I would like to post a bank account object to intuit payments using Alamofire, however I keep getting the following error:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
The documentation notes the following:
REQUEST URL
Sandbox Base URL: https://sandbox.api.intuit.com
Production Base URL: https://api.intuit.com
Operation: POST /quickbooks/v4/customers/<id>/bank-accounts
Content type: application/json
Header Parameters:
Request-Id required
Query Parameters:
id required
Request body
{
"name": "My Checking",
"routingNumber": "XXXXX0358",
"accountNumber": "XXXX4534",
"accountType": "PERSONAL_CHECKING",
"phone": "6047296480"
}
My attempts are as follows:
func saveBankAccountToIntuitPayments() {
let url = "https://api.intuit.com/quickbooks/v4/customers/" + userID! + "/bank-accounts"
let parameters: Parameters = [
"name": "John Doe",
"routingNumber": "123321456",
"accountNumber": "432123789012",
"accountType": "PERSONAL_CHECKING",
"phone": "55568925029"
]
ATTEMPT 1
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
ATTEMPT 2
let requestId = userID! + getTimeNow()
let header = [ "Request-Id" : requestId ]
Alamofire.request(url: url, method: .post, headers: header, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
ATTEMPT 3
request(url, method: .post, parameters: parameters, headers: header).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
}
This is the code for my json parser:
func parseData(JSONData: Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
print("printing readable JSON (below)")
print(readableJSON ?? "no JSON data was returned")
} catch {
print("errror occured (below)")
print(error)
}
}