[Flutter] 메소드 채널을 사용해 파일을 앱에 공유해보자

zunu·2023년 2월 7일
0
post-thumbnail

보통 앱에서 공유하기를 통해 다른 앱으로 보내거나 메모 또는 앨범으로 옮기는 작업을 많이 하는데, 나는 반대로 앱을 켜지 않은 상태에서 앱으로 공유하기를 통해 파일을 앱으로 가져와야 했다.(IOS)

해서 방법을 찾아보았는데 따로 라이브러리가 있지는 않았고 할 수 있는 방법을 찾아서 여기에 작성한다.

우선 Runner.xcworkspace를 열어 Info.plist를 아래와 같이 변경해주었다.
나 같은 경우 압축파일을 공유해야해서 ZIP을 넣어주었다.

그렇게 되면 일단 zip 파일을 앱에 공유할 수는 있게 될 것이다.

이런식으로. 하지만 선택을 해도 앱이 실행될 뿐 별 다른 작동은 하지 않을 것이다. 그러므로 앱에 파일을 공유했을 때 어떤 동작을 할지 코드를 작성해주어야 한다.

나는 Runner.xcworkspace로 가서 AppDelegate.swift에 작성해주었다.

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    var url: URL = URL(fileURLWithPath: "")
    var shareChannel = FlutterMethodChannel()
    
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        shareChannel = FlutterMethodChannel(name: "메소드 채널 URL", binaryMessenger: controller.binaryMessenger)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        self.url = url
        shareChannel.setMethodCallHandler({[weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
          // This method is invoked on the UI thread.
          guard call.method == "getShareURL" else {
              result(FlutterMethodNotImplemented)
            return
          }
          self?.receiveShareURL(result: result)
        })
        return true
    }
    
    private func receiveShareURL(result: FlutterResult) {
        var res : String = url.absoluteString
        result(res)
    }
}

이 부분은 메소드 채널 사용 방법과도 관련이 있는데 아래 링크를 확인해 더 공부할 것을 권한다.
출처-https://flutter-ko.dev/docs/development/platform-integration/platform-channels

그리고 플러터 프로젝트로 다시 이동하여

const shareURL = MethodChannel('메소드 채널 URL');
String? _filePath = "";
this._filePath = await shareURL.invokeMethod('getShareURL');

이렇게만 해주면 현재 공유된 파일을 가져오게된다.

profile
개발새발

0개의 댓글