Here is a basic code snippet that uses Alamofire to upload document onto a server.
fileprivate func uploadDocument(_ file: Data,filename : String,handler : @escaping (String) -> Void) {
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(file, withName: "upload_data" , fileName: filename, mimeType: "application/pdf")
},
to: "https://yourserverurl", method: .post , headers: headers)
.response { response in
if let data = response.data{
//handle the response however you like
}
}
}
Note that the Mime Type should be modified depending on the type of document to be uploaded. Follow this link to see the list of mime type.
Integrating with UIDocumentPickerController
Most of the time, we need to upload document onto the server by choosing a local file from the phone. This is done using the UIDocumentPickerController
. For example, let's assume that I have a button in my ViewController
that brings up the UIDocumentPickerController
when pressed:
button.addAction(for: .touchUpInside) {
let importMenu = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
self.present(importMenu, animated: true, completion: nil)
}
Next, we have to make our ViewController
conform to UIDocumentPickerDelegate
, and get the document URL:
extension IndividualChatViewController:UIDocumentPickerDelegate{
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let documentURL = urls.first else {
return
}
}
}
Now that we got the url of the document, we have to retrieve the document using the url in order to get the document in the type of Data.
fileprivate func getDocumentFromURL(URL: NSURL,handler : @escaping (Data) -> Void) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: URL as URL)
request.httpMethod = "GET"
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error == nil) {
// Success
DispatchQueue.main.async(execute: {
//this is an async operation, use handler to handle the result
handler(data!)
})
}
else {
// Failure
print("Failure: %@", error!.localizedDescription)
}
})
task.resume()
}
Top comments (1)
this is really helpful ,
but if we want to use URL Sessions ,
so how can we done this task using URL Session