receive_sharing_intent 1.0.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new73

receive_sharing_intent #

A flutter plugin that enables flutter apps to receive sharing photos from other apps.

Also, supports iOS Share extension and launching the host app automatically. Check the provided example for more info.

1.0.0 #

  • Add support for urls

0.9.2 #

  • Remove un-necessary jar libraries

0.9.1 #

  • Fix issue where sharing in iOS simulator does not work

example/README.md

receive_sharing_intent_example #

Android #

android/app/src/main/manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
.....
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  <application
        android:name="io.flutter.app.FlutterApplication"
        ...
        >

    <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>
      </activity>
      
  </application>
</manifest>
....

iOS #

1. Add the following #

ios/Runner/info.plist

...
<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>SharePhotos</string>
			</array>
		</dict>
		<dict/>
	</array>

  <key>NSPhotoLibraryUsageDescription</key>
	<string>To upload photos, please allow permission to access your photo library.</string>
...

2. Create Share Extension #

  • Using xcode, go to File/New/Target and Choose "Share Extension"
  • Give it a name i.e. "Share Extension"
Add the following code: #

ios/Share Extension/info.plist

....
	<string>$(FLUTTER_BUILD_NAME)</string>
	<key>CFBundleVersion</key>
	<string>$(FLUTTER_BUILD_NUMBER)</string>
	<key>NSExtension</key>
	<dict>
		<key>NSExtensionAttributes</key>
        <dict>
            <key>NSExtensionActivationRule</key>
            <dict>
                <key>NSExtensionActivationSupportsImageWithMaxCount</key>
                <integer>100</integer>
            </dict>
        </dict>
		<key>NSExtensionMainStoryboard</key>
		<string>MainInterface</string>
		<key>NSExtensionPointIdentifier</key>
		<string>com.apple.share-services</string>
	</dict>
....

ios/Share Extension/ShareViewContriller.swift


import UIKit
import Social
import MobileCoreServices
import Photos

class ShareViewController: SLComposeServiceViewController {

    let sharedKey = "ImageSharePhotoKey"
    var imagesData: [String] = []
    
    override func isContentValid() -> Bool {
        return true
    }
    
    override func viewDidLoad() {
        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
        
        if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
            let contentType = kUTTypeImage as String
            
            if let contents = content.attachments {
                for (index, attachment) in (contents as! [NSItemProvider]).enumerated() {
                    if attachment.hasItemConformingToTypeIdentifier(contentType) {
                        attachment.loadItem(forTypeIdentifier: contentType, options: nil) { [weak self] data, error in
                            
                            if error == nil, let url = data as? URL, let this = self {

                                for component in url.path.components(separatedBy: "/") where component.contains("IMG_") {
                                    
                                    // photo: /var/mobile/Media/DCIM/101APPLE/IMG_1320.PNG
                                    // edited photo: /var/mobile/Media/PhotoData/Mutations/DCIM/101APPLE/IMG_1309/Adjustments/FullSizeRender.jpg
                                    
                                    // cut file's suffix if have, get file name like IMG_1309.
                                    let fileName = component.components(separatedBy: ".").first!
                                    if let asset = this.imageAssetDictionary[fileName] {
                                        this.imagesData.append( asset.localIdentifier)
                                    }
                                    break
                                }
                                
                                // If this is the last item, save imagesData in userDefaults and redirect to host app
                                if index == (content.attachments?.count)! - 1 {
                                     // TODO: IMPROTANT: This should be your host app bundle identiefier
                                    let hostAppBundleIdentiefier = "com.kasem.sharing"
                                    let userDefaults = UserDefaults(suiteName: "group.\(hostAppBundleIdentiefier)")
                                    userDefaults?.set(this.imagesData, forKey: this.sharedKey)
                                    userDefaults?.synchronize()
                                    this.redirectToHostApp()
                                    this.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
                                }
                                
                            } else {
                                print("GETTING ERROR")
                                let alert = UIAlertController(title: "Error", message: "Error loading image", preferredStyle: .alert)
                                
                                let action = UIAlertAction(title: "Error", style: .cancel) { _ in
                                    self?.dismiss(animated: true, completion: nil)
                                }
                                
                                alert.addAction(action)
                                self?.present(alert, animated: true, completion: nil)
                                self?.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
                            }
                        }
                    }
                }
            }
        }
    }
    
    override func configurationItems() -> [Any]! {
        // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
        return []
    }
    
    private func redirectToHostApp() {
        let url = URL(string: "SharePhotos://dataUrl=\(sharedKey)")
        var responder = self as UIResponder?
        let selectorOpenURL = sel_registerName("openURL:")
        
        while (responder != nil) {
            if (responder?.responds(to: selectorOpenURL))! {
                let _ = responder?.perform(selectorOpenURL, with: url)
            }
            responder = responder!.next
        }
    }
    
    /// Key is the matched asset's original file name without suffix. E.g. IMG_193
    private lazy var imageAssetDictionary: [String : PHAsset] = {
        
        let options = PHFetchOptions()
        options.includeHiddenAssets = true
        
        let fetchResult = PHAsset.fetchAssets(with: options)
        
        var assetDictionary = [String : PHAsset]()
        
        for i in 0 ..< fetchResult.count {
            let asset = fetchResult[i]
            let fileName = asset.value(forKey: "filename") as! String
            let fileNameWithoutSuffix = fileName.components(separatedBy: ".").first!
            assetDictionary[fileNameWithoutSuffix] = asset
        }
        
        return assetDictionary
    }()
}

3. Add Runner and Share Extension in the same group #

  • Go to the Capabilities tab and switch on the App Groups switch for both targets. Add a new group and name it group.YOUR_HOST_APP_BUNDLE_IDENTIFIER in my case group.com.kasem.sharing

4. Compiling issues and their fixes #

  • Error: App does not build after adding Share Extension?

  • Fix: Check Build Settings of your share extension and remove everything that tries to import Cocoapods from your main project. i.e. under Linking/Other Linker Flags

  • You might need to disable bitcode for the extension target

  • Error: Invalid Bundle. The bundle at 'Runner.app/Plugins/Sharing Extension.appex' contains disallowed file 'Frameworks'

  • Fix: https://stackoverflow.com/a/25789145/2061365

Full Example #


import 'package:flutter/material.dart';
import 'dart:async';

import 'package:receive_sharing_intent/receive_sharing_intent.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StreamSubscription _intentDataStreamSubscription;
  List<Uri> _sharedFiles;

  @override
  void initState() {
    super.initState();

    // For sharing images coming from outside the app while the app is in the memory
    _intentDataStreamSubscription =
        ReceiveSharingIntent.getIntentDataStreamAsUri().listen(
            (List<Uri> uris) {
      _sharedFiles = uris;
    }, onError: (err) {
      print("Latest Intent Data error: $err");
    });

    // For sharing images coming from outside the app while the app is closed
    ReceiveSharingIntent.getInitialIntentDataAsUri().then((List<Uri> uris) {
      _sharedFiles = uris;
    });
  }

  @override
  void dispose() {
    _intentDataStreamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Number of shared files: ${_sharedFiles?.length ?? 0}'),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  receive_sharing_intent: ^1.0.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:receive_sharing_intent/receive_sharing_intent.dart';
  
Version Uploaded Documentation Archive
1.0.0 Jun 15, 2019 Go to the documentation of receive_sharing_intent 1.0.0 Download receive_sharing_intent 1.0.0 archive
0.9.2 Jun 12, 2019 Go to the documentation of receive_sharing_intent 0.9.2 Download receive_sharing_intent 0.9.2 archive
0.9.1 May 30, 2019 Go to the documentation of receive_sharing_intent 0.9.1 Download receive_sharing_intent 0.9.1 archive
0.9.0 May 30, 2019 Go to the documentation of receive_sharing_intent 0.9.0 Download receive_sharing_intent 0.9.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
49
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95
Overall:
Weighted score of the above. [more]
73
Learn more about scoring.

We analyzed this package on Jun 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.3.2
  • pana: 0.12.18
  • Flutter: 1.5.4-hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/receive_sharing_intent.dart.

Run flutter format to format lib/receive_sharing_intent.dart.

Maintenance issues and suggestions

Support latest dependencies. (-5 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test