How to upload document to server using Alamofire
Tags: swift, alamofire
Published: 2020-04-19 18:30:00

---
date: 2020-04-19 18:30
description: Upload document such as PDF using Alamofire
tags: swift,alamofire
---

Here is a basic code snippet that uses Alamofire to upload document onto a server.

```swift
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 
               }

       }
   }
```
<br/>

Note that the Mime Type should be modified depending on the type of document to be uploaded. Follow this [link](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) to see the list of mime type. 


<br/>

## 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: 

```swift
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)
}
```
<br/>

Next, we have to make our `ViewController` conform to `UIDocumentPickerDelegate`, and get the document URL: 

```swift
extension IndividualChatViewController:UIDocumentPickerDelegate{

    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let documentURL = urls.first else {
               return
        }
        
    }
}
```
<br/>

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. 

```swift
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()
}
```