Validate a CSV File in Swift

Cloudmersive
2 min readApr 14, 2021

While CSV files can be great for organizing large amounts of data, they aren’t exactly known for their simplicity. Due to their complex design, it can be a common occurrence to receive an invalid error for a CSV document, which can really throw a wrench in your productivity for the day. Utilizing an API to automatically validate a CSV file can be the perfect solution to enable you to speed up the process and identify the errors that are holding you up.

To perform the validation in Swift, all you need is the following code, the CSV file you want to validate, and the API key.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)let parameters = [
[
"key": "inputFile",
"src": "/path/to/file",
"type": "file"
]] as [[String : Any]]
let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if param["contentType"] != nil {
body += "\r\nContent-Type: \(param["contentType"] as! String)"
}
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body += "\r\n\r\n\(paramValue)\r\n"
} else {
let paramSrc = param["src"] as! String
let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
let fileContent = String(data: fileData, encoding: .utf8)!
body += "; filename=\"\(paramSrc)\"\r\n"
+ "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
}
}
}
body += "--\(boundary)--\r\n";
let postData = body.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/convert/validate/csv")!,timeoutInterval: Double.infinity)
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()

And we’re done! You can review the results to determine how you can fix the identified errors if the file is invalid. To retrieve your API key, head to the Cloudmersive website to register for a free account; this will give you access to 800 calls/month across our entire API library.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.