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

Viewed 375

I have created a VC with a print and share friendly version of a bunch of calculations. When I press "share" there appears the little icon and all the share options which is great. I cannot figure out how to add a filename of some kind beside the little icon. I think this would look much more professional if I could get this accomplished.

Hope there is a simple solution someone could help with :)

enter image description here

Here is my code:

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)
}
}
1 Answers

First save the UIImage as a temporary png/jpg file:

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

Then save it as a temporary file, which lets you to choose a file name:

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

Then you can share the URL instead:

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

P.S. the file is only temporary.

Related