FRAMEWORK/FLUTTER

[Flutter] 누구나 할수있는 플루터에서 url로 파일 다운로드하기

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2022. 4. 18. 16:46
728x90

 

생각보다 오래걸린 파일 다운로드하기

 

 

1. 관련 dependencies 받기

dependencies:
	path_provider: ^2.0.9
    flutter_downloader: ^1.7.3

 

flutter_downloader

말 그대로 파일 다운받을 수 있게 도와주는 패키지

https://pub.dev/packages/flutter_downloader

 

path_provider

경로 가져오는 패키지

https://pub.dev/packages/path_provider

 

 

2. IOS 및 Android 설정하기

 

IOS

더보기

<Tagets - Signing & Capabilities>

 

Remote notifications 와 Background processing 체크!

 

<Tagets - General>

 

Farameworks, Libraries, and Embedded Content에서 libsqlite3.tbd 추가

 

 

 

 

 

 

<App Delegate>

 

App Delegate에서 flutter download에 관한 부분을 추가해준다! 

나는 이 프로젝트에서 카카오 로그인이랑 네이버 로그인을 동시에 사용하는 중이라 둘이 로그인 충돌때문에 추가적으로 네이버 관련 코드를 넣어두었는데 신경쓰지않아도 된다!

 

import UIKit
import Flutter
import flutter_downloader
import NaverThirdPartyLogin

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
//    if #available(iOS 10.0, *) {
//        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
//    }
    
    GeneratedPluginRegistrant.register(with: self)
    FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

   override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    if (url.absoluteString.contains("thirdPartyLoginResult")) {
        return NaverThirdPartyLoginConnection.getSharedInstance().application(app, open: url, options: options)
    }
    return super.application(app, open: url, options: options)

  }
}
private func registerPlugins(registry: FlutterPluginRegistry) {
    if (!registry.hasPlugin("FlutterDownloaderPlugin")) {
       FlutterDownloaderPlugin.register(with: registry.registrar(forPlugin: "FlutterDownloaderPlugin")!)
    }
}

 

<Info.plist>

 

선택적인 부분이라 나는 따로 설정해준 부분이 없다 

http 관련 설정이었는데 자세한건 공식문서에서 확인 할 수 있다!

 

Android

더보기

<AndroidManifest.xml>

manifest에 관련 정보만 추가해주면 끝!

<provider
        android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
        android:authorities="${applicationId}.flutter_downloader.provider"
        android:exported="false"
        android:grantUriPermissions="true">
    <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
</provider>

 

 

3. Flutter에서 사용하기

 

먼저 main.dart에서 init을 해주어야된다

import 'package:flutter_downloader/flutter_downloader.dart';


WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(
  debug: true
);

 

그리고 사용하고자하는 곳에서 사용해주면되는데 

여기서 주의할점은 사용하는곳에서 callback부분을 먼저 선언해주어야된다는점!

이거때문에 꽤 많은 시간을 소모하였다 ㅠㅠ

 

 

 


import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';

@override
void initState() {
    // TODO: implement initState
    super.initState();

	FlutterDownloader.registerCallback(downloadCallback);

}

...
GestureDetector(
	onTap: () async{
        String dir = (await getApplicationDocumentsDirectory()).path; 	//path provider로 저장할 경로 가져오기 
        try{
          await FlutterDownloader.enqueue(
            url: "${file.src}", 	// file url
            savedDir: '$dir/',	// 저장할 dir
            fileName: '${file.originFileName}',	// 파일명
            saveInPublicStorage: true ,	// 동일한 파일 있을 경우 덮어쓰기 없으면 오류발생함!
          );


          print("파일 다운로드 완료");
        }catch(e){
          print("eerror :::: $e");
        }
    }
    ...
)


... 

static void downloadCallback(
  String id, DownloadTaskStatus status, int progress) {
	print('Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
	final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
	send.send([id, status, progress]);
}

 

 

이렇게 하면 파일 내가 지정한 경로에 파일이 다운로드된다! 

728x90