【问题标题】:How do I share files using share sheet in iOS?如何在 iOS 中使用共享表共享文件?
【发布时间】:2016-03-07 18:25:18
【问题描述】:

我想使用 iPhone 上的共享工作表功能共享我在应用程序中本地拥有的一些文件。我在UIWebView 中显示文件,当用户单击共享表时,我想显示选项(电子邮件、WhatsApp 等)以共享UIWebView 上显示的文件。我知道我们可以使用

func displayShareSheet(shareContent:String) {                                                                           
    let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
    presentViewController(activityViewController, animated: true, completion: {})    
}

例如共享一个字符串。如何更改此代码以共享文档?

【问题讨论】:

    标签: ios swift uiwebview ios-sharesheet


    【解决方案1】:

    Swift 4.2Swift 5

    如果您在目录中已有文件并想共享它,只需将其 URL 添加到 activityItems

    let fileURL = NSURL(fileURLWithPath: "The path where the file you want to share is located")
    
    // Create the Array which includes the files you want to share
    var filesToShare = [Any]()
    
    // Add the path of the file to the Array
    filesToShare.append(fileURL)
    
    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
    
    // Show the share-view
    self.present(activityViewController, animated: true, completion: nil)
    

    如果需要制作文件

    我正在使用此扩展程序从Data 创建文件(阅读代码中的 cmets 以了解其工作原理):

    如 typedef 的回答,获取当前文档目录:

    /// Get the current directory
    ///
    /// - Returns: the Current directory in NSURL
    func getDocumentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory as NSString
    }
    

    Data 的扩展名:

    extension Data {
    
        /// Data into file
        ///
        /// - Parameters:
        ///   - fileName: the Name of the file you want to write
        /// - Returns: Returns the URL where the new file is located in NSURL
        func dataToFile(fileName: String) -> NSURL? {
    
            // Make a constant from the data
            let data = self
    
            // Make the file path (with the filename) where the file will be loacated after it is created
            let filePath = getDocumentsDirectory().appendingPathComponent(fileName)
    
            do {
                // Write the file from data into the filepath (if there will be an error, the code jumps to the catch block below)
                try data.write(to: URL(fileURLWithPath: filePath))
    
                // Returns the URL where the new file is located in NSURL
                return NSURL(fileURLWithPath: filePath)
    
            } catch {
                // Prints the localized description of the error from the do block
                print("Error writing the file: \(error.localizedDescription)")
            }
    
            // Returns nil if there was an error in the do-catch -block
            return nil
    
        }
    
    }
    

    使用示例

    分享图片文件

    // Your image
    let yourImage = UIImage()
    

    在 png 文件中

    // Convert the image into png image data
    let pngImageData = yourImage.pngData()
    
    // Write the png image into a filepath and return the filepath in NSURL
    let pngImageURL = pngImageData?.dataToFile(fileName: "nameOfYourImageFile.png")
    
    // Create the Array which includes the files you want to share
    var filesToShare = [Any]()
    
    // Add the path of png image to the Array
    filesToShare.append(pngImageURL!)
    
    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
    
    // Show the share-view
    self.present(activityViewController, animated: true, completion: nil)
    

    在 jpg 文件中

    // Convert the image into jpeg image data. compressionQuality is the quality-compression ratio in % (from 0.0 (0%) to 1.0 (100%)); 1 is the best quality but have bigger filesize
    let jpgImageData = yourImage.jpegData(compressionQuality: 1.0)
    
    // Write the jpg image into a filepath and return the filepath in NSURL
    let jpgImageURL = jpgImageData?.dataToFile(fileName: "nameOfYourImageFile.jpg")
    
    // Create the Array which includes the files you want to share
    var filesToShare = [Any]()
    
    // Add the path of jpg image to the Array
    filesToShare.append(jpgImageURL!)
    
    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
    
    // Show the share-view
    self.present(activityViewController, animated: true, completion: nil)
    

    分享文本文件

    // Your String including the text you want share in a file
    let text = "yourText"
    
    // Convert the String into Data
    let textData = text.data(using: .utf8)
    
    // Write the text into a filepath and return the filepath in NSURL
    // Specify the file type you want the file be by changing the end of the filename (.txt, .json, .pdf...)
    let textURL = textData?.dataToFile(fileName: "nameOfYourFile.txt")
    
    // Create the Array which includes the files you want to share
    var filesToShare = [Any]()
    
    // Add the path of the text file to the Array
    filesToShare.append(textURL!)
    
    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
    
    // Show the share-view
    self.present(activityViewController, animated: true, completion: nil)
    

    其他文件

    你可以用Data格式的任何东西创建一个文件,据我所知,Swift中的几乎所有东西都可以转换成Data,比如StringIntDouble、@987654336 @...:

    // the Data you want to share as a file
    let data = Data()
    
    // Write the data into a filepath and return the filepath in NSURL
    // Change the file-extension to specify the filetype (.txt, .json, .pdf, .png, .jpg, .tiff...)
    let fileURL = data.dataToFile(fileName: "nameOfYourFile.extension")
    
    // Create the Array which includes the files you want to share
    var filesToShare = [Any]()
    
    // Add the path of the file to the Array
    filesToShare.append(fileURL!)
    
    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
    
    // Show the share-view
    self.present(activityViewController, animated: true, completion: nil)
    

    【讨论】:

    • 这是 Swift 4 的绝佳答案 - 适用于所有不同的文件类型
    • 确保在 ipad 的情况下使用“activityViewController.popoverPresentationController?.sourceView = button or view”
    • 文件分享后不应该删除吗?我试图将它放入完成处理程序中,但事实证明它在实际共享之前被删除,而不是之后。所以我们不删除?它不会被自动删除,它怎么知道什么时候? 困惑
    【解决方案2】:

    我想分享我的 UIActivityViewController 解决方案并将文本分享为图像文件。此解决方案适用于通过邮件共享,甚至保存到 Dropbox。

    @IBAction func shareCsv(sender: AnyObject) {
        //Your CSV text
        let str = self.descriptionText.text!
        filename = getDocumentsDirectory().stringByAppendingPathComponent("file.png")
    
        do {
            try str.writeToFile(filename!, atomically: true, encoding: NSUTF8StringEncoding)
    
            let fileURL = NSURL(fileURLWithPath: filename!)
    
            let objectsToShare = [fileURL]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    
            self.presentViewController(activityVC, animated: true, completion: nil)
    
        } catch {
            print("cannot write file")
            // failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
        }
    
    }
    
    func getDocumentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }
    

    【讨论】:

      【解决方案3】:

      这是 Swift 3 版本:

      let dictToSave: [String: Any] = [
          "someKey": "someValue"
      ]
      
      let jsonData = try JSONSerialization.data(withJSONObject: dictToSave, options: .prettyPrinted)
      
      let filename = "\(self.getDocumentsDirectory())/filename.extension"
      let fileURL = URL(fileURLWithPath: filename)
      try jsonData.write(to: fileURL, options: .atomic)
      
      let vc = UIActivityViewController(activityItems: [fileURL], applicationActivities: [])
      
      self.present(vc, animated: true)
      
      
      func getDocumentsDirectory() -> String {
          let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
          let documentsDirectory = paths[0]
          return documentsDirectory
      }
      

      【讨论】:

      • 像魅力一样工作。谢谢,这是非常好的代码,比官方文档更容易理解。
      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多