sunil kumar
sunil kumar

Reputation: 63

How to Upload file Doc/pdf/excel from iphone device into the backend using swift?

i need to take the attachment which may be doc/pdf/excel file from the iphone and then send to the backend Please guide if anyone knows how to to do this

let me tell you what i did yet 1.i have been using UIDocumentPickerViewController

  1. the below function to open the iCloud

func clickFunction(){

 let options = [kUTTypePDF as String, kUTTypeZipArchive  as String, kUTTypePNG as String, kUTTypeJPEG as String, kUTTypeText  as String, kUTTypePlainText as String]

     let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: options, in: .import)

    documentPicker.delegate = self

    documentPicker.modalPresentationStyle = .formSheet

    self.present(documentPicker, animated: true, completion: nil)
}

3.These are the delegate methods

public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

    guard let myURL = urls.first else {
        return
    }

    print("import result : \(myURL)")
}



public func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
}





func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    print("view was cancelled")
    dismiss(animated: true, completion: nil)
}

from the above code i am getting the url after selecting any file from the icloud i am little confuse what should i do with that url

like:- file:///private/var/mobile/Containers/Data/Application/8F334336-525D-46F7-BF60-79FC6A45601A/tmp/com.Empro.WorkToday-Inbox/AbhishekSharma-MCA-1.pdf

Upvotes: 1

Views: 1011

Answers (1)

Chandaboy
Chandaboy

Reputation: 1359

when ever file has been selected you have to upload it on Moya it is very good network layer for uploading image/ doc etc file to server

 let keyValue = "doc[0]"
   
var multipartData = [MultipartFormData]()



if(docTypes == .isTypePDF)
    {
        multipartData.append(Moya.MultipartFormData(provider: .data(documentData!), name: keyValue, fileName: "file.pdf", mimeType: "application/pdf"))
    }
    else
    {
        multipartData.append(Moya.MultipartFormData(provider: .data(documentData!), name: keyValue, fileName: "file.doc", mimeType: "application/doc"))
    }

when docuemnt Selected under this delegate you need to convert it into Data

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        
        if(urls.count > 0)
        {
            do
            {
                let imageExtensions = ["pdf", "rtf", "docx", "doc"]

                for i in 0..<urls.count
                {
                    let urlvalue = urls[i]
                   
                    let pathExtention = urlvalue.pathExtension
                    if imageExtensions.contains(pathExtention)
                    {
                        print("Image URL: \(urlvalue)")
                        
                        if(pathExtention == "pdf")
                        {
                            self.doctype = .isTypePDF
                        }
                        else
                        {
                            self.doctype = .isTypeDoc
                        }
                        
                        // Do something with it
                    }else
                    {
                       print("Movie URL: \(urlvalue)")
                    }
                    
                    let fileName = urlvalue.lastPathComponent

                    let imgData1 = try Data.init(contentsOf: urlvalue)
                    print("testing")
                    
                    self.documentData = imgData1
                    
                    self.uploadDocumentName = fileName
                    self.tableView.reloadData()
                   // multipartData.append(Moya.MultipartFormData(provider: .data(imgData1), name: "audio[0]", fileName: "file.mp4", mimeType: "audio/mpeg"))
                }
            }
            catch {
                print("asdfasfd")
            }
        }
        
    }

and using this upload function you will send that file to server

func updatePostData(formdata: [MultipartFormData], controller: UIViewController)
{
    provider.request( .UpdatePost(formdata) , callbackQueue: DispatchQueue.main, progress: { (progress) in
        
        print(progress.progress)

    }) { (result) in
         
        switch result{
        case .success(let response):
            
            do {
              loadLoader(isLoading: false)
              
              let responseResult = try response.map(BaseCordableResponseResult<Any>.self)
              print(responseResult)
              
//              self.delegateObject?.reloadData()

                NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)

               controller.dismiss(animated: true)
                                 
            } catch {
              
               controller.dismiss(animated: true)

            }

        case .failure(let error):
            checkLogoutUser(error: error, viewController: controller)

        }
    }
}

Upvotes: 1

Related Questions