Skip to content

Instantly share code, notes, and snippets.

@FabP93
Last active March 22, 2021 13:20
Show Gist options
  • Save FabP93/d03d062723bf403c25089367e8504ad7 to your computer and use it in GitHub Desktop.
Save FabP93/d03d062723bf403c25089367e8504ad7 to your computer and use it in GitHub Desktop.
ShareExtension - ShareViewController part 2
private func handleSharedFile() {
// extracting the path to the URL that is being shared
let attachments = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments ?? []
let contentType = kUTTypeData as String
for provider in attachments {
// Check if the content type is the same as we expected
if provider.hasItemConformingToTypeIdentifier(contentType) {
provider.loadItem(forTypeIdentifier: contentType,
options: nil) { [unowned self] (data, error) in
// Handle the error here if you want
guard error == nil else { return }
if let url = data as? URL,
let imageData = try? Data(contentsOf: url) {
self.save(imageData, key: "imageData", value: imageData)
} else {
// Handle this situation as you prefer
fatalError("Impossible to save image")
}
}}
}
}
private func save(_ data: Data, key: String, value: Any) {
// You must use the userdefaults of an app group, otherwise the main app don't have access to it.
let userDefaults = UserDefaults(suiteName: appGroupName)
userDefaults.set(data, forKey: key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment