profile

Expo(React Native) で Safari からリンクをシェアできるようにする

Published at

2025/04/11

Updated at

2025/04/11

Written by

marromugi

あまり記事が見当たらなかったのでメモです。
Safari などの外部のアプリから、Expo のアプリにリンクや画像を共有する手順をまとめます。
超簡潔に書くと、手順は以下の通りです。(プロジェクトはすでに作られている前提で進めます)
  • ビルドして xcodeproj を生成
  • xcodeproj を開いて、Share Extension を作成する

ビルドしてxcodeproj を生成

以下のコマンドで prebuild します。
$ npx expo prebuild
prebuild が完了すると、ルート直下に /ios というディレクトリが作成されます。
このディレクトリ配下に {project_name}.xcodeproj が生成されるので、このプロジェクトから Share Extension の実装を進めていきます。

xcodeproj を開いて、ShareExtension を作成する

作成した xcodeproj を Xcode で開きます。
Xcode を開いたら、ヘッダーメニューから File > New > Target をクリック。
iOS のタブから、Share Extension をクリックして Next をクリック。
image.png
Product Nameは任意の名前をつけて大丈夫です。
今回は testShareExtension という名前をつけます。
作成すると
Activate “atestShareExtension” scheme?
と聞かれるので、Activate をクリックします。
Xcode 上で実装した内容がちゃんと反映されるか確かめるために、ちょっとだけ編集します。
testShareExtension/ShareViewController.swift を開いて、末尾に以下の実装を加えます。
//
//  ShareViewController.swift
//  testShareExtension
//
//  Created by 清水智輝 on 2025/04/11.
//

import UIKit
import Social

class ShareViewController: SLComposeServiceViewController {

    override func isContentValid() -> Bool {
        // Do validation of contentText and/or NSExtensionContext attachments here
        return true
    }

    override func didSelectPost() {
        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
    
        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
        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 []
    }
  
    // 以下から追加
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "テスト"
    }
}
追記したら保存して、expo のプロジェクトに戻ります。
戻ったら、以下のコマンドで iOS Simulator を起動します。
npx expo run:ios
実行ログには、以下のように先ほど作成した ShareExtension が含まれていることが確認できます。
> [email protected] ios /Users/marromugi/xxx/apps/mobile
> expo run:ios

env: load .env
 Planning build
 Linking   utakata/testShareExtension » testShareExtension.debug.dylib
 Linking   utakata/testShareExtension » testShareExtension
 Preparing utakata/testShareExtension » Info.plist
 Signing   utakata/testShareExtension » testShareExtension.debug.dylib
シュミレーターが起動したら、Safari を開いてページを共有してみます。
すると、共有先のアプリ一覧に expo でビルドしたアプリが含まれています。
スクリーンショット 2025-04-11 23.27.14.png
共有すると、以下のようにモーダルが開きます。
タイトルがテストになっており、実装した内容が反映されていることが確認できます。
スクリーンショット 2025-04-11 23.29.08.png

おわり

ネイティブむずかしい