How do I share files using share sheet in IOS?

uiactivityviewcontroller
ios share extension
ios share sheet
uiactivityviewcontroller email subject
uiactivityviewcontroller share image and text objective-c
uiactivityviewcontroller save to files
ios share extension raywenderlich
share sheet ios 13 swift

I want to share some files I have locally in my App using Share Sheet functionality in iPhone. I display the file in a UIWebview and when the user click the share sheet, I want to show options (email, whats app etc ) to share the file displayed on the UIWebView. I know that we can use

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

to share string for example. How do I change this code to share documents?

Thanks in advance.

I want to share my solution of UIActivityViewController and sharing text as a image file. This solution works for sharing via Mail and even Save to 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
}

UIActivityViewController Tutorial: Sharing Data, As I read in this article : iOS 13: The Ars Technica review. I want to be able to display this menu with all the share options available in my SwiftUI app: So, even easier, how can I simply share a link - a text - to another App with Swift 5 using SwiftUI? What is the new It's on my list of bug reports to file now. That list's getting� Use this section to perform actions using the item you want to share, like copying its URL or using it with a shortcut. In an app, tap the available share button. Scroll to the bottom of the share sheet and tap Edit Actions. Tap, hold, and drag the handles on one of your Favorites to change its position on your Favorites list.

Swift 4.2 and Swift 5

If you already have a file in a directory and want to share it, just add it's URL into 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)

If you need to make the file:

I'm using this extension to make files from Data (read the comments in the code for explanation how it works):

As in the typedef's answer, get the current documents directory:

/// 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
}

Extension for 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

    }

}

Examples how to use:

Share image-files:

// Your image
let yourImage = UIImage()

in png-file

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

in jpg-file

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

Share text-files:

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

Other files:

You can make a file from anything which is in Data format and as far as I know, almost everything in Swift can be converted into Data like String, Int, Double, Any...:

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

How can create a share sheet/view …, Prior to iOS 13 and iPadOS 13, the Share Sheet on iPhone and iPad hasn't lets you send a webpage as either a PDF or a web archive file). If you have questions about using the updated share sheet in iOS 13 and� If you want to upload, download, or share files using cellular data, open Settings, select Cellular, scroll down to iCloud Drive and any third-party cloud services you use, and turn it on for each service. If you don't want to access your iCloud Drive files in the Files app, you can choose to download and add only third-party cloud services

Here's the Swift 3 version:

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
}

How to customize and use the share sheet in iOS 13 and iPadOS 13 , This class, UIActivityViewController , can handle sharing text, URLs, image, and more, In this article I'll walk through some complete examples of using However, the default share sheet for images will offer users the chance to So, open your project's Info.plist file, select any item, click +, then choose� With iOS 13, the share sheet has become “intelligent”, as it suggests your favorite contacts at the top. Then, we have a section for various apps such as AirDrop, Messages, Notes, and others. Moving even further down (by dragging up), there is a slew of additional options, depending on which apps you have.

UIActivityViewController by example – Hacking with Swift, Apple is changing the way the Share button works in iOS 13 and iPadOS. save things to different storage services, as well as makes it easy to share files. in how the Share Sheet you summon using the Share button looks. When you change the order of the icons in the Share sheet, the changes will remain regardless which app you’re using. How to edit the Share sheet in iOS. To edit the Share sheet in iOS, you can open it from any app. However, we recommend you open it by trying to share a pic from the Photos app or a photo from an iMessage in the Messages app.

How to use the new Share button in iOS 13, iPadOS, Using this new panel, you can quickly share the selected data in a Messages thread without searching for the contact (like you had to in iOS 12). Using AirDrop with iOS. Sending files via AirDrop on the iPhone could not be any easier. When you want to send anything with AirDrop, you will need to pull up the “Share Sheet.” Generally speaking, that can be found using the same icon that the Mac has, the square with the arrow pointing up out of it.

How to Customize the Share Sheet on Your iPhone or iPad, Introduced in iOS 8, the sharing system — which other apps can work with via a tool called "share sheets" — in iOS lets you send documents,� Please note that in the Action Sheet, you can only rearrange those options that are added to favorites. That’s all, mate! This is how you can customize the Share Sheet on your iPhone or iPad. I do not use Messages, so I have this at last. Similarly, I use actions like Save to Files and Add to Album a lot. So, they are on top of my favorites.

Comments
  • this is an excellent answer for Swift 4 - works perfectly for all different file types
  • Works like a charm. Thanks, that's very nice code and easier to understand than official documentation.