16

What I want

On an Iphone, when visiting a website inside Safari or Chrome, it is possible to share content to other apps. In this case, you can see I can share the content (basically the URL) to an app called Pocket.

Pocket example

Is it possible to do that? And specifically with Cordova?

Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419

5 Answers5

25

Edit: sooner or later a simple mobile website will probably be able to receive content shared from native apps. Check the Web Share Target protocol

I'm answering my own question, as we finally succeeded implementing the iOS Share Extension for a Cordova application.

First the Share Extension system is only available for iOS >= 8

However it is kind of painful to integrate it in a Cordova project because there's no special Cordova config to do so. When creating a Share Extension, it is hard for the Cordova team to reverse-engineer the XCode xproj file to add a share extension so it will probably be hard in the future too...

You have 2 options:

  • Version some of your iOS platform files (like the xproj file)
  • Include a manual procedure after generating the iOS platform with cordova

We decided to go with the 2nd option, as our extension is pretty stable and we will not modify it often.

Create the share extension manually

VERY IMPORTANT: create the share extension, and the Action.js THROUGH the XCode interface! They have to be registered in the xproj file or it won't work at all. See

Create the files through XCode

To create a share extension for a Cordova app, you will have to do like any iOS developer would do.

  • Open the ios platform xproj on XCode
  • File > New > Target > Share Extension
  • Select Swift as a language (only because ObjC seems unpleasant to me)

You get a new folder in XCode with some files that you will have to customize.

You will also need an extra Action.js file in that share extension folder. Create a new empty file (through XCode!) Action.js

Handle browser data extraction

Put in Action.js the following code:

var Action = function() {};

Action.prototype = {

run: function(parameters) {
    parameters.completionFunction({"url": document.URL, "title": document.title });
},

finalize: function(parameters) {

}

};

var ExtensionPreprocessingJS = new Action

When your share extension is selected on top of a browser (I think it only works for Safari), this JS will be run and will permit you to retrieve the data you want on that page in your Swift controller (here I want the url and the title).

Customize Info.plist

Now you need to customize the Info.plist file to describe what kind of share extension you are creating, and what kind of content you can share to your app. In my case I mostly want to share urls, so here is a config that works for sharing urls from Chrome or Safari.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>CFBundleDevelopmentRegion</key>
   <string>en</string>
   <key>CFBundleDisplayName</key>
   <string>MyClipper</string>
   <key>CFBundleExecutable</key>
   <string>$(EXECUTABLE_NAME)</string>
   <key>CFBundleIdentifier</key>
   <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
   <key>CFBundleInfoDictionaryVersion</key>
   <string>6.0</string>
   <key>CFBundleName</key>
   <string>$(PRODUCT_NAME)</string>
   <key>CFBundlePackageType</key>
   <string>XPC!</string>
   <key>CFBundleShortVersionString</key>
   <string>1.0</string>
   <key>CFBundleSignature</key>
   <string>????</string>
   <key>CFBundleVersion</key>
   <string>1</string>
   <key>NSExtension</key>
   <dict>
      <key>NSExtensionAttributes</key>
      <dict>
         <key>NSExtensionJavaScriptPreprocessingFile</key>
         <string>Action</string>
         <key>NSExtensionActivationRule</key>
         <dict>
            <key>NSExtensionActivationSupportsText</key>
            <true/>
            <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
            <integer>1</integer>
         </dict>
      </dict>
      <key>NSExtensionMainStoryboard</key>
      <string>MainInterface</string>
      <key>NSExtensionPointIdentifier</key>
      <string>com.apple.share-services</string>
   </dict>
</dict>
</plist>

Notice that we registered the Action.js file in that plist file.

Customize the ShareViewController.swift

Normally you would have to implement by yourself Swift views that will be run on top of the existing app (for me on top of the browser app).

By default, the controller will provide a default view that you can use, and you can perform requests to your backend from there. Here is an example from which I inspired myself that do so.

But in my case, I am not an iOS developer and I want that when the user select my extension, it opens my app instead of displaying iOS views. So I used a custom URL scheme to open my app clipper: myAppScheme://openClipper?url=SomeUrl This permits me to design my clipper in HTML / JS instead of having to create iOS views.

Notice that I use a hack for that, and Apple may forbid to open your app from a Share Extension in future iOS versions. However this hack works currently for iOS 8.x and 9.0.

Here is the code. It works for both Chrome and Safari on iOS.

//
//  ShareViewController.swift
//  MyClipper
//
//  Created by Sébastien Lorber on 15/10/2015.
//
//

import UIKit
import Social
import MobileCoreServices

@available(iOSApplicationExtension 8.0, *)
class ShareViewController: SLComposeServiceViewController {

    let contentTypeList = kUTTypePropertyList as String
    let contentTypeTitle = "public.plain-text"
    let contentTypeUrl = "public.url"

    // We don't want to show the view actually
    // as we directly open our app!
    override func viewWillAppear(animated: Bool) {
        self.view.hidden = true
        self.cancel()
        self.doClipping()
    }

    // We directly forward all the values retrieved from Action.js to our app
    private func doClipping() {
        self.loadJsExtensionValues { dict in
            let url = "myAppScheme://mobileclipper?" + self.dictionaryToQueryString(dict)
            self.doOpenUrl(url)
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////

    private func dictionaryToQueryString(dict: Dictionary<String,String>) -> String {
        return dict.map({ entry in
            let value = entry.1
            let valueEncoded = value.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            return entry.0 + "=" + valueEncoded!
        }).joinWithSeparator("&")
    }

    // See https://github.com/extendedmind/extendedmind/blob/master/frontend/cordova/app/platforms/ios/extmd-share/ShareViewController.swift
    private func loadJsExtensionValues(f: Dictionary<String,String> -> Void) {
        let content = extensionContext!.inputItems[0] as! NSExtensionItem
        if (self.hasAttachmentOfType(content, contentType: contentTypeList)) {
            self.loadJsDictionnary(content) { dict in
                f(dict)
            }
        } else {
            self.loadUTIDictionnary(content) { dict in
                // 2 Items should be in dict to launch clipper opening : url and title.
                if (dict.count==2) { f(dict) }
            }
        }
    }

    private func hasAttachmentOfType(content: NSExtensionItem,contentType: String) -> Bool {
        for attachment in content.attachments as! [NSItemProvider] {
            if attachment.hasItemConformingToTypeIdentifier(contentType) {
                return true;
            }
        }
        return false;
    }

    private func loadJsDictionnary(content: NSExtensionItem,f: Dictionary<String,String> -> Void)  {
        for attachment in content.attachments as! [NSItemProvider] {
            if attachment.hasItemConformingToTypeIdentifier(contentTypeList) {
                attachment.loadItemForTypeIdentifier(contentTypeList, options: nil) { data, error in
                    if ( error == nil && data != nil ) {
                        let jsDict = data as! NSDictionary
                        if let jsPreprocessingResults = jsDict[NSExtensionJavaScriptPreprocessingResultsKey] {
                            let values = jsPreprocessingResults as! Dictionary<String,String>
                            f(values)
                        }
                    }
                }
            }
        }
    }


    private func loadUTIDictionnary(content: NSExtensionItem,f: Dictionary<String,String> -> Void) {
        var dict = Dictionary<String, String>()
        loadUTIString(content, utiKey: contentTypeUrl   , handler: { url_NSSecureCoding in
            let url_NSurl = url_NSSecureCoding as! NSURL
            let url_String = url_NSurl.absoluteString as String
            dict["url"] = url_String
            f(dict)
        })
        loadUTIString(content, utiKey: contentTypeTitle, handler: { title_NSSecureCoding in
            let title = title_NSSecureCoding as! String
            dict["title"] = title
            f(dict)
        })
    }


    private func loadUTIString(content: NSExtensionItem,utiKey: String,handler: NSSecureCoding -> Void) {
        for attachment in content.attachments as! [NSItemProvider] {
            if attachment.hasItemConformingToTypeIdentifier(utiKey) {
                attachment.loadItemForTypeIdentifier(utiKey, options: nil, completionHandler: { (data, error) -> Void in
                    if ( error == nil && data != nil ) {
                        handler(data!)
                    }
                })
            }
        }
    }


    // See https://stackoverflow.com/a/28037297/82609
    // Works fine for iOS 8.x and 9.0 but may not work anymore in the future :(
    private func doOpenUrl(url: String) {
        let urlNS = NSURL(string: url)!
        var responder = self as UIResponder?
        while (responder != nil){
            if responder!.respondsToSelector(Selector("openURL:")) == true{
                responder!.callSelector(Selector("openURL:"), object: urlNS, delay: 0)
            }
            responder = responder!.nextResponder()
        }
    }
}

// See https://stackoverflow.com/a/28037297/82609
extension NSObject {
    func callSelector(selector: Selector, object: AnyObject?, delay: NSTimeInterval) {
        let delay = delay * Double(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
        dispatch_after(time, dispatch_get_main_queue(), {
            NSThread.detachNewThreadSelector(selector, toTarget:self, withObject: object)
        })
    }
}

Notice there are 2 ways to load the Dictionary<String,String>. This is because Chrome and Safari seems to provide the url and title of the page in 2 different ways.

Automating the process

You must create the Share Extension files and Action.js file through the XCode interface. However, once they are created (and referenced in XCode), you can replace them with your own files.

So we decided that we will version the above files in a folder (/cordova/ios-share-extension), and override the default share extension files with them.

This is not ideal but the minimum procedure we use is:

  • Build Cordova iOS platform (cordova prepare ios)
  • Open project in XCode
  • Create share extension with (product name="MyClipper", language="Swift", organization name="MyCompany")
  • On the "MyClipper", create an empty file "Action.js"
  • Copy the content of /cordova/ios-share-extension to cordova/platforms/ios/MyClipper

This way the extension is correctly registered in the xproj file but you still have the ability to version control your extension.

Edit 2017: this may become easier to setup all that with cordova-ios@5.0.0, see https://issues.apache.org/jira/browse/CB-10218

cnmuc
  • 6,025
  • 2
  • 24
  • 29
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
  • Thanks! Very helpful! – Flock Dawson Dec 16 '15 at 07:53
  • 1
    Thank you very much, this was the only post on SO with anything useful related to original question. I required handling URL+text+image in various combinations and created a derivation of this answer to do so. Just to pay it forward, https://github.com/inshikos/cordova-ios-share-extension/blob/master/ShareExtension/ShareViewController.swift might be of help to others needing a solution for content sharing to a Cordova app in the absence of a proper iOS share extension plugin. – Warren Kim Jan 20 '16 at 08:34
  • thanks @WarrenKim your code could be helpful to me in the future too :) – Sebastien Lorber Jan 20 '16 at 09:23
  • Hey @SebastienLorber ! Your post seems really helpful :) Thanks! One thing I'd like to ask: I did everything like you described, but still can't see an icon of my app in sharing screen. Could you please point me where it may stuck ? – Stanislav Iegorov Apr 08 '16 at 14:10
  • @StanislavIegorov I have no idea. Maybe you did not set target >= 7.0 in XCode, or missed a step – Sebastien Lorber Apr 08 '16 at 14:20
  • @SebastienLorber, thanks for reply :) After many attempts I finally figured out what was wrong - in XCode window it is A MUST to Set active scheme to newly created Share extension and it works. But it's still unclear how to deploy created Share extension with an app itself, because as I got it - you can't simply deploy extension without containing app. Thanks! – Stanislav Iegorov Apr 18 '16 at 09:28
  • @SebastienLorber, I want to share image from iOS photos app to my Cordova iOS app. Do I need to use share extenstion here also? If that is the case, then how can I access cordova plugins in that iOS share extension? Please help me. I am in very critical situation. – Sivakumar Apr 25 '16 at 07:20
  • @Sivakumar I have no idea, I only expose here what I had to do. Look at code of Warren-kim above as it seems it handles images sharing – Sebastien Lorber Apr 25 '16 at 08:33
  • @SebastienLorber, I have followed this link http://lokesh-patel.blogspot.in/2015/11/ios-phonegap-app-share-extension-images.html. In this shareDemo is a share extension and it is being triggered when photos are shared from gallery. Then I can do only JS related stuff. I not able to access any of the cordova plugin. My requirement is only to access Cordova plugins in shareDemo share extension. – Sivakumar Apr 25 '16 at 09:00
  • @WarrenKim, Could you please help me out? – Sivakumar Apr 25 '16 at 09:01
  • @Sivakumar, I'm not sure what you mean by "only JS related stuff" and "access any of cordova plugin" with respect to your issue. Maybe this writeup can help you? https://www.inshikos.com/blogs/76/dev/link-and-photo-sharing-to-a-cordova-ios-app-via-share-extensions-ios-8 – Warren Kim Apr 30 '16 at 04:31
  • @SebastienLorber Thanks Sebastien. This works really well. Did you have any issues building in xcode after adding the extension. Specifically: 'Cordova/CDV.h' file not found – Jamie Carruthers Aug 03 '16 at 14:12
  • We had a lot of different issues of this kind. If you also have `failed to import bridging header` maybe you should add "CordovaLib" in the Target Dependencies of your extension, using XCode. It solved this error for us on ios platform >= 4.x – Sebastien Lorber Aug 03 '16 at 15:51
  • @SebastienLorber My app is showing in popup but i am not able to open my application on click of that. Can you please suggest me to figure out the solution. – Mss iOS Feb 28 '17 at 05:01
  • @MssiOS sorry I'm not working on share extension anymore. You should first make sure that your custom url sheme does work and permit to open your app. Maybe there are additional logs that you can setup and look at to debug the problem. I've written everything that I know on the subject here, can't help more than that. – Sebastien Lorber Feb 28 '17 at 12:03
3

doOpenUrl() above needs to be updated to work on iOS 10. The following code also works on older versions of iOS.

private func doOpenUrl(url: String) {

    let url = NSURL(string:url)
    let context = NSExtensionContext()
    context.open(url! as URL, completionHandler: nil)

    var responder = self as UIResponder?

    while (responder != nil){
        if responder?.responds(to: Selector("openURL:")) == true{
            responder?.perform(Selector("openURL:"), with: url)
        }
        responder = responder!.next
    }
}
Aaron Rosen
  • 141
  • 1
  • 4
  • how to do this "doOpenUrl() above needs to be updated to work on iOS 10."? after paste those codes, i've got many red dot. – crapthings Mar 02 '17 at 03:53
1

You should be able to achieve your goal with far less manual work using this cordova plugin. It'll also work on Android.

jeko
  • 307
  • 2
  • 8
  • Using your plugin with capacitor 3 its working for Images and Videos. But I am unable to get `text / URL` from any application. My specific target is to get Post URL from Instagram. – Najam Us Saqib Aug 21 '21 at 10:56
1

That's a good and still relevant question.

I tried to make use of the awesome cordova-plugin-openwith by Jean-Christophe Hoelt but faced several issues. The plugin is meant to receive share items of one type (say, URL, text or image), which is configured during installation. Also, with its current implementation, writing a note to share and selecting a receiver in a Cordova app are two different steps in different (native and Cordova) context, so it didn't look as a good user experience to me.

I made these and other corrections to this plugin and published it as a separate plugin: https://github.com/EternallLight/cordova-plugin-openwith-ios

Note that it works only for iOS, not for Android.

EternalLight
  • 1,323
  • 1
  • 11
  • 19
0

Following up on the iOS 10 update remark by Aaron Rosen, here's the process to make it work :

  1. In the code from the original answer by Sebastien Lorber, update the doOpenUrl function as suggested by Aaron. Reposting here for clarity:

    private func doOpenUrl(url: String) {
    let url = NSURL(string:url)
    let context = NSExtensionContext()
    context.open(url! as URL, completionHandler: nil)
    var responder = self as UIResponder?
    while (responder != nil){
        if responder?.responds(to: Selector("openURL:")) == true{
            responder?.perform(Selector("openURL:"), with: url)
        }
        responder = responder!.next
    }
    }
    
  2. Follow the process outlined in the initial answer to create the extension in Xcode

  3. Select ShareViewController.swift in the extension folder
  4. Go to Edit > Convert > To Current Swift Syntax
  5. In the extension build settings, toggle "Require Only App-Extension-Safe API" to NO.

Only then will the extension work.

  • With this solution, it works on simulator but not on real device. Any idea why ? – Djiggy Sep 15 '17 at 16:24
  • It's impossible to tell you why just based on this comment, but you can try debugging the javascript in Safari : make sure your phone is plugged in and Safari has developer mode enabled (preferences -> advanced). When you launch the app your phone will appear in the developer menu of Safari and you can inspect the webview and check the console there for errors. Hopefully you'll have relevant info. Check the logs in Xcode also they can contain relevant info. Make sure also that the extension is properly signed. – Edward Silhol Sep 18 '17 at 16:55
  • Thanks for you response. Unfortunaltely all seems to be ok in the app (no errors in safari/xcode logs), moreover, my custom url starts application from safari but not from gallery. I continue my investigation ! – Djiggy Sep 19 '17 at 08:01
  • 1
    Ok, that's no surprise. So far we've only handled opening URLs from Safari, been too busy to work on it more. If you find out how to handle them from other apps, I'd love to hear how ! – Edward Silhol Sep 20 '17 at 10:53