通过 UIActivityView 共享时如何为屏幕截图文件指定文件名

How do I give screenshot file a filename when sharing via UIActivityView

我创建了一个 VC,其中包含一堆计算的打印和共享友好版本。当我按下“分享”时,会出现小图标和所有很棒的分享选项。我不知道如何在小图标旁边添加某种文件名。我想如果我能做到这一点,这看起来会更专业。

希望有人可以提供一个简单的解决方案:)

这是我的代码:

import UIKit

class EvenPrintableViewController: UIViewController {

@IBOutlet weak var widthSizeTransfer: UILabel!
@IBOutlet weak var heightSizeTransfer: UILabel!
@IBOutlet weak var lengthTransfer: UILabel!
@IBOutlet weak var calcOutput: UILabel!

// Instantiate variables for Even transfer
var largeSizeRelay: String?
var lengthSizeRelay: String?
var heightRelay: String?
var calcOutputRelay: String?

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Sets share icon to share/print view
    navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
    
    // Assign labels to Metric Even VC values via instances above
    widthSizeTransfer.text = witdhSizeRelay
    heightSizeTransfer.text = heightSizeRelay
    heightTransfer.text = heightRelay
    calcOutput.text = calcOutputRelay

}

// Share function for share button
@objc func shareTapped() {
    
    let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
    let image = renderer.image { ctx in
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
    }

    let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
    vc.excludedActivityTypes = [.assignToContact, .addToReadingList]
    vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
    present(vc, animated: true)
}
}

首先将 UIImage 保存为临时 png/jpg 文件:

guard let imageData = image.pngData() else { return }

然后保存为临时文件,可以选择文件名:

let tempDir = FileManager.default.temporaryDirectory
let imgFileName = "YOUR_IMG_FILE_NAME.png"
let tempImgDir = tempDir.appendingPathComponent(imgFileName)
try? imageData.write(to: tempImgDir)

那么你可以分享URL:

// Your code
let vc = UIActivityViewController(activityItems: [tempImgDir], applicationActivities: [])

P.S。该文件只是临时文件。