Zum Inhalt springen

Erste Schritte mit Share Target

Dieser Leitfaden führt Sie durch die Integration des Capacitor Share Target-Plugins, damit Ihre App freigegebene Inhalte von anderen Anwendungen empfangen kann.

Installieren Sie das Plugin mit npm:

Terminal-Fenster
npm install @capgo/capacitor-share-target
npx cap sync

Fügen Sie Ihrem AndroidManifest.xml im Tag <activity> Absichtsfilter hinzu:

<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
<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>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>

Für iOS müssen Sie eine Share-Erweiterung erstellen:

  1. Öffnen Sie Ihr Projekt in Xcode
  2. Gehen Sie zu Datei > Neu > Ziel
  3. Wählen Sie Erweiterung teilen und klicken Sie auf Weiter
  4. Benennen Sie es (z. B. „ShareExtension“) und klicken Sie auf Fertig stellen
  5. Wenn Sie dazu aufgefordert werden, aktivieren Sie das Schema
  1. Gehen Sie in Ihrem Haupt-App-Ziel zu Signaturen und Funktionen
  2. Klicken Sie auf *+ Capability und fügen Sie App-Gruppen hinzu.
  3. Erstellen oder wählen Sie eine App-Gruppe aus (z. B. group.com.yourcompany.yourapp).
  4. Wiederholen Sie den Vorgang für das Share Extension-Ziel

Die Share-Erweiterung muss freigegebene Daten im App-Gruppencontainer speichern, damit Ihre Haupt-App darauf zugreifen kann.

Ausführliche Informationen zur Einrichtung von iOS finden Sie in der Share Extension-Dokumentation von Apple.

import { CapacitorShareTarget } from '@capgo/capacitor-share-target';
CapacitorShareTarget.addListener('shareReceived', (event) => {
console.log('Received share event');
console.log('Title:', event.title);
console.log('Texts:', event.texts);
// Handle shared files
if (event.files && event.files.length > 0) {
event.files.forEach(file => {
console.log(`File: ${file.name}`);
console.log(`Type: ${file.mimeType}`);
console.log(`URI: ${file.uri}`);
});
}
});

Hier ist ein umfassendes Beispiel für den Umgang mit verschiedenen Arten von geteilten Inhalten:

import { CapacitorShareTarget } from '@capgo/capacitor-share-target';
class ShareTargetService {
private listener: any;
initialize() {
this.listener = CapacitorShareTarget.addListener('shareReceived', (event) => {
this.handleSharedContent(event);
});
console.log('Share target listener initialized');
}
handleSharedContent(event: any) {
console.log('=== Share Received ===');
// Handle title
if (event.title) {
console.log('Title:', event.title);
this.showNotification('Shared: ' + event.title);
}
// Handle text content
if (event.texts && event.texts.length > 0) {
event.texts.forEach((text: string, index: number) => {
console.log(`Text ${index + 1}:`, text);
this.processSharedText(text);
});
}
// Handle files
if (event.files && event.files.length > 0) {
console.log(`Received ${event.files.length} file(s)`);
event.files.forEach((file: any) => {
console.log('File details:');
console.log(' Name:', file.name);
console.log(' Type:', file.mimeType);
console.log(' URI:', file.uri);
this.processSharedFile(file);
});
}
}
processSharedText(text: string) {
// Check if it's a URL
if (this.isURL(text)) {
console.log('Shared URL detected:', text);
// Handle URL (e.g., create bookmark)
this.saveBookmark(text);
} else {
console.log('Shared text detected');
// Handle plain text (e.g., create note)
this.createNote(text);
}
}
processSharedFile(file: any) {
const fileType = file.mimeType.split('/')[0];
switch (fileType) {
case 'image':
console.log('Processing shared image');
this.handleImage(file);
break;
case 'video':
console.log('Processing shared video');
this.handleVideo(file);
break;
case 'audio':
console.log('Processing shared audio');
this.handleAudio(file);
break;
case 'application':
console.log('Processing shared document');
this.handleDocument(file);
break;
default:
console.log('Processing generic file');
this.handleGenericFile(file);
}
}
handleImage(file: any) {
// Process image file
console.log('Saving image:', file.name);
// Implementation: Save to gallery, upload, etc.
}
handleVideo(file: any) {
// Process video file
console.log('Saving video:', file.name);
}
handleAudio(file: any) {
// Process audio file
console.log('Saving audio:', file.name);
}
handleDocument(file: any) {
// Process document file
console.log('Saving document:', file.name);
}
handleGenericFile(file: any) {
// Process generic file
console.log('Saving file:', file.name);
}
isURL(text: string): boolean {
try {
new URL(text);
return true;
} catch {
return false;
}
}
saveBookmark(url: string) {
console.log('Creating bookmark for:', url);
// Implementation
}
createNote(text: string) {
console.log('Creating note with text:', text.substring(0, 50));
// Implementation
}
showNotification(message: string) {
console.log('Notification:', message);
// Show toast or notification
}
cleanup() {
if (this.listener) {
this.listener.remove();
}
}
}
// Usage
const shareTarget = new ShareTargetService();
shareTarget.initialize();
// Cleanup when app closes
// shareTarget.cleanup();
import { useEffect } from 'react';
import { CapacitorShareTarget } from '@capgo/capacitor-share-target';
function useShareTarget(onShareReceived: (event: any) => void) {
useEffect(() => {
const listener = CapacitorShareTarget.addListener('shareReceived', onShareReceived);
return () => {
listener.remove();
};
}, [onShareReceived]);
}
// Usage in component
function App() {
useShareTarget((event) => {
console.log('Share received:', event);
// Handle shared content
});
return <div>Your App</div>;
}
import { onMounted, onUnmounted } from 'vue';
import { CapacitorShareTarget } from '@capgo/capacitor-share-target';
export default {
setup() {
let listener: any;
onMounted(() => {
listener = CapacitorShareTarget.addListener('shareReceived', (event) => {
console.log('Share received:', event);
// Handle shared content
});
});
onUnmounted(() => {
if (listener) {
listener.remove();
}
});
}
};
if (event.texts && event.texts.length > 0) {
const text = event.texts[0];
if (text.startsWith('http://') || text.startsWith('https://')) {
// Handle URL
window.open(text, '_blank');
}
}
if (event.files) {
const images = event.files.filter(f => f.mimeType.startsWith('image/'));
images.forEach(async (image) => {
// Read and display image
const response = await fetch(image.uri);
const blob = await response.blob();
const imageUrl = URL.createObjectURL(blob);
// Display or process image
console.log('Image URL:', imageUrl);
});
}
if (event.files && event.files.length > 1) {
console.log(`Processing ${event.files.length} files`);
const processPromises = event.files.map(file =>
processFile(file)
);
await Promise.all(processPromises);
console.log('All files processed');
}
  1. Mehrere Inhaltstypen verarbeiten: Seien Sie auf den Empfang von Texten, URLs und Dateien vorbereitet
  2. Inhalt validieren: Überprüfen Sie die MIME-Typen vor der Verarbeitung
  3. Feedback geben: Zeigen Sie den Benutzern, was sie erhalten haben
  4. Fehlerbehandlung: Datei-URIs sind möglicherweise ungültig oder nicht zugänglich
  5. Listener bereinigen: Entfernen Sie Listener, wenn sie nicht benötigt werden
  6. Gründlich testen: Testen Sie mit verschiedenen Apps und Inhaltstypen
  7. Berechtigungen anfordern: Für einige Dateitypen sind möglicherweise zusätzliche Berechtigungen erforderlich

Stellen Sie sicher, dass Absichtsfilter in AndroidManifest.xml im Tag <activity> mit android.intent.action.MAIN korrekt konfiguriert sind.

iOS Freigabeerweiterung wird nicht angezeigt

Section titled “iOS Freigabeerweiterung wird nicht angezeigt”
  1. Stellen Sie sicher, dass die App-Gruppe in beiden Zielen konfiguriert ist
  2. Stellen Sie sicher, dass die Share-Erweiterung aktiviert ist
  3. Überprüfen Sie, ob Info.plist in der Share Extension die richtige Konfiguration hat
try {
const response = await fetch(file.uri);
const blob = await response.blob();
// Process blob
} catch (error) {
console.error('Failed to access file:', error);
// Show error to user
}
  • Entdecken Sie die API-Referenz für eine vollständige Methodendokumentation
  • Sehen Sie sich die Beispiel-App für eine erweiterte Nutzung an – Vollständige Implementierungsbeispiele finden Sie im Tutorial.