如何在iOS中使用共享表共享文件?

kcugc4gi  于 2023-05-23  发布在  iOS
关注(0)|答案(3)|浏览(227)

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

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

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

niknxzdl

niknxzdl1#

Swift 4.2和Swift 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)

// Be notified of the result when the share sheet is dismissed
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
    ...
}

// Show the share-view
self.present(activityViewController, animated: true, completion: nil)

如果需要制作文件

我使用这个扩展来从Data创建文件(阅读代码中的注解以解释它的工作原理):
正如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,比如StringIntDoubleAny ...:

// 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)
jdgnovmf

jdgnovmf2#

我想分享我的解决方案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
}
p8ekf7hl

p8ekf7hl3#

以下是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
}

相关问题