Skip to content

Repository files navigation

Send-Intent

This is a Capacitor plugin meant to be used in Ionic applications for checking if your App was targeted as a share goal. It supports both Android and iOS and is able to handle a single file or multiple files of any type.

Check out my app mindlib - your personal mind library to see it in action.

Projects below Capacitor 3

For projects below Capacitor 3 please use "send-intent": "1.1.7"!

Installation

npm install @mindlib-capacitor/send-intent
npx cap sync

Usage

Import & Sample call

Shared files will be received as URI-String. You can use Capacitor's Filesystem plugin to get the files content. The "url"-property of the SendIntent result is also used for web urls, e.g. when sharing a website via browser, so it is not necessarily a file path. Make sure to handle this either through checking the "type"-property or by error handling!

import{SendIntent}from"@mindlib-capacitor/send-intent";SendIntent.checkSendIntentReceived().then((result: any)=>{if(result){console.log('SendIntent received');console.log(JSON.stringify(result));}if(result.url){letresultUrl=decodeURIComponent(result.url);Filesystem.readFile({path: resultUrl}).then((content)=>{console.log(content.data);}).catch((err)=>console.error(err));}}).catch(err=>console.error(err));

Android

Configure a new activity in AndroidManifest.xml!

<!-- Your actual activity declaration -->
<activityandroid:name=".MainActivity"
...
...
...>
</activity>
<!-- Add new One Activity for handle Intent here -->
<activityandroid:name="de.mindlib.sendIntent.SendIntentActivity" <!-- Do not change this name, otherwise your application will crash -->
android:label="@string/app_name"
android:exported="true"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<actionandroid:name="android.intent.action.SEND" />
<categoryandroid:name="android.intent.category.DEFAULT" />
<!-- Depending on your project, you can add here the type of data you wish to receive -->
<dataandroid:mimeType="text/plain" />
<dataandroid:mimeType="image/*" />
<dataandroid:mimeType="application/*" />
<dataandroid:mimeType="video/*" />
</intent-filter>
</activity>

On Android, I strongly recommend closing the send-intent-activity after you have processed the send-intent in your app. Not doing this can lead to app state issues (because you have two instances running) or trigger the same intent again if your app reloads from idle mode. You can close the send-intent-activity by calling the "finish"-method:

SendIntent.finish();

However, if you want to stay in your app after the send-intent, there is a solution using Deep Links which was worked out here: mindlib-capacitor#69 (comment)

iOS

Create a "Share Extension" (Creating an App extension) and make sure that the extensions "iOS deployment target" version is in sync with your apps deployment target version!

Set the activation rules in the extensions Info.plist, so that your app will be displayed as share option!

...
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsFileWithMaxCount</key>
<integer>5</integer>
<key>NSExtensionActivationSupportsImageWithMaxCount</key>
<integer>5</integer>
<key>NSExtensionActivationSupportsMovieWithMaxCount</key>
<integer>5</integer>
<key>NSExtensionActivationSupportsText</key>
<true/>
<key>NSExtensionActivationSupportsWebPageWithMaxCount</key>
<integer>1</integer>
<key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
<integer>1</integer>
<key>NSExtensionActivationUsesStrictMatching</key>
<false/>
</dict>
... 

Code for the ShareViewController:

//
// ShareViewController.swift
// mindlib
//
// Created by Carsten Klaffke on 05.07.20.
//
import MobileCoreServices
import Social
import UIKit
classShareItem{publicvartitle:String?publicvartype:String?publicvarurl:String?}classShareViewController:UIViewController{privatevarshareItems:[ShareItem]=[]overridepublicfunc viewDidAppear(_ animated:Bool){
super.viewDidAppear(animated)self.extensionContext!.completeRequest(returningItems:[], completionHandler:nil)}privatefunc sendData(){letqueryItems= shareItems.map{[URLQueryItem(
name:"title",
value: $0.title?.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)??""),URLQueryItem(name:"description", value:""),URLQueryItem(
name:"type",
value: $0.type?.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)??""),URLQueryItem(
name:"url",
value: $0.url?.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)??""),]}.flatMap({ $0 })varurlComps=URLComponents(string:"YOUR_APP_URL_SCHEME://")!
urlComps.queryItems = queryItems
openURL(urlComps.url!)}fileprivatefunc createSharedFileUrl(_ url:URL?)->String{letfileManager=FileManager.default
letcopyFileUrl=
fileManager.containerURL(forSecurityApplicationGroupIdentifier:"YOUR_APP_GROUP_ID")!
.absoluteString.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)! + url!
.lastPathComponent.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)!
try? fileManager.copyItem(at: url!, to:URL(string: copyFileUrl)!)return copyFileUrl
}func saveScreenshot(_ image:UIImage, _ index:Int)->String{letfileManager=FileManager.default
letcopyFileUrl=
fileManager.containerURL(forSecurityApplicationGroupIdentifier:"YOUR_APP_GROUP_ID")!
.absoluteString.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)!
+"/screenshot_\(index).png"do{try image.pngData()?.write(to:URL(string: copyFileUrl)!)return copyFileUrl
}catch{print(error.localizedDescription)return""}}fileprivatefunc handleTypeUrl(_ attachment:NSItemProvider)asyncthrows->ShareItem{letresults=tryawait attachment.loadItem(forTypeIdentifier: kUTTypeURL asString, options:nil)leturl= results as!URL?letshareItem:ShareItem=ShareItem()if url!.isFileURL {
shareItem.title = url!.lastPathComponent
shareItem.type ="application/"+ url!.pathExtension.lowercased()
shareItem.url =createSharedFileUrl(url)}else{
shareItem.title = url!.absoluteString
shareItem.url = url!.absoluteString
shareItem.type ="text/plain"}return shareItem
}fileprivatefunc handleTypeText(_ attachment:NSItemProvider)asyncthrows->ShareItem{letresults=tryawait attachment.loadItem(forTypeIdentifier: kUTTypeText asString, options:nil)letshareItem:ShareItem=ShareItem()lettext= results as!String
shareItem.title = text
shareItem.type ="text/plain"return shareItem
}fileprivatefunc handleTypeMovie(_ attachment:NSItemProvider)asyncthrows->ShareItem{letresults=tryawait attachment.loadItem(forTypeIdentifier: kUTTypeMovie asString, options:nil)letshareItem:ShareItem=ShareItem()leturl= results as!URL?
shareItem.title = url!.lastPathComponent
shareItem.type ="video/"+ url!.pathExtension.lowercased()
shareItem.url =createSharedFileUrl(url)return shareItem
}fileprivatefunc handleTypeImage(_ attachment:NSItemProvider, _ index:Int)asyncthrows->ShareItem{letdata=tryawait attachment.loadItem(forTypeIdentifier: kUTTypeImage asString, options:nil)letshareItem:ShareItem=ShareItem()switch data {caseletimage as UIImage:
shareItem.title ="screenshot_\(index)"
shareItem.type ="image/png"
shareItem.url =self.saveScreenshot(image, index)caseleturl as URL:
shareItem.title = url.lastPathComponent
shareItem.type ="image/"+ url.pathExtension.lowercased()
shareItem.url =self.createSharedFileUrl(url)default:print("Unexpected image data:",type(of: data))}return shareItem
}overridepublicfunc viewDidLoad(){
super.viewDidLoad()
shareItems.removeAll()letextensionItem= extensionContext?.inputItems[0]as!NSExtensionItemTask{tryawaitwithThrowingTaskGroup(
of:ShareItem.self,
body:{ taskGroup infor(index, attachment)in extensionItem.attachments!.enumerated(){if attachment.hasItemConformingToTypeIdentifier(kUTTypeURL asString){
taskGroup.addTask{returntryawaitself.handleTypeUrl(attachment)}}elseif attachment.hasItemConformingToTypeIdentifier(kUTTypeText asString){
taskGroup.addTask{returntryawaitself.handleTypeText(attachment)}}elseif attachment.hasItemConformingToTypeIdentifier(kUTTypeMovie asString){
taskGroup.addTask{returntryawaitself.handleTypeMovie(attachment)}}elseif attachment.hasItemConformingToTypeIdentifier(kUTTypeImage asString){
taskGroup.addTask{returntryawaitself.handleTypeImage(attachment, index)}}}fortryawaititemin taskGroup {self.shareItems.append(item)}})self.sendData()}}@objcfunc openURL(_ url:URL){varresponder:UIResponder?=selfwhile responder !=nil{iflet application = responder as?UIApplication{
application.open(url, options:[:], completionHandler:nil)return}
responder = responder?.next
}}}

The share extension is like a little standalone program, so to get to your app the extension has to make an openURL call. In order to make your app reachable by a URL, you have to define a URL scheme (Register Your URL Scheme). The code above calls a URL scheme named "YOUR_APP_URL_SCHEME" (first line in "didSelectPost"), so just replace this with your scheme! To allow sharing of files between the extension and your main app, you need to create an app group which is checked for both your extension and main app. Replace "YOUR_APP_GROUP_ID" in "setSharedFileUrl()" with your app groups name.

Finally, in your AppDelegate.swift, override the following function like this:

import SendIntent
import Capacitor
// ...
@UIApplicationMainclassAppDelegate:UIResponder,UIApplicationDelegate{
// ...
letstore=ShareStore.store
// ...
func application(_ app:UIApplication, open url:URL, options:[UIApplication.OpenURLOptionsKey:Any]=[:])->Bool{varsuccess=trueifCAPBridge.handleOpenUrl(url, options){
success =ApplicationDelegateProxy.shared.application(app, open: url, options: options)}guardlet components =NSURLComponents(url: url, resolvingAgainstBaseURL:true),let params = components.queryItems else{returnfalse}lettitles= params.filter{ $0.name =="title"}letdescriptions= params.filter{ $0.name =="description"}lettypes= params.filter{ $0.name =="type"}leturls= params.filter{ $0.name =="url"}
store.shareItems.removeAll()if(titles.count >0){forindexin0...titles.count-1{varshareItem:JSObject=JSObject()shareItem["title"]=titles[index].value!
shareItem["description"]=descriptions[index].value!
shareItem["type"]=types[index].value!
shareItem["url"]=urls[index].value!
store.shareItems.append(shareItem)}}
store.processed =falseletnc=NotificationCenter.default
nc.post(name:Notification.Name("triggerSendIntent"), object:nil)return success
}
// ...
}

This is the function started when an application is open by URL.

Make sure to register the following event-listener! Otherwise you will miss the event fired in the plugin:

window.addEventListener("sendIntentReceived",()=>{Plugins.SendIntent.checkSendIntentReceived().then((result: any)=>{if(result){// ...}});})

You should also exceute a call on app startup as described in Usage, because on a cold start the event-listener might not be registered early enough (see [mindlib-capacitor#57]).

Donation

If you want to support my work, you can donate me via Lightning (Bitcoin) or Stripe.

Lightning: mostroll13@walletofsatoshi.com

Donate me a coffee on Stripe

Consulting

I work as a freelance IT Consultant. If you need help with this plugin or want me to do the complete setup in your App, you can contact me at mail@carsten-klaffke.de.

About

Repository for send-intent Capacitor plugin

Resources

Code of conduct

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages