How to implement cross-platform folder picker in tauri for Desktop and Android? #10860
-
I want user to pick folder so I can get path of this folder. For desktop Im using #[tauri::command]
pub fn select_directory() -> Result<PathBuf, Error> {
if cfg!(target_os = "android") {
select_directory_android()
} else {
select_directory_desktop()
}
}
#[cfg(target_os = "android")]
fn select_directory_android() -> Result<PathBuf, Error> {
use jni::objects::{JClass, JString};
use jni::JNIEnv;
use ndk_glue::native_activity;
use std::ffi::CString;
use std::sync::Once;
static INIT: Once = Once::new();
static mut SELECTED_DIRECTORY: Option<PathBuf> = None;
#[no_mangle]
pub extern "system" fn Java_com_tauri_dev_DirectoryPickerActivity_sendDirectoryPathToRust(
env: JNIEnv,
_class: JClass,
directory_path: JString,
) {
let path: String = env
.get_string(directory_path)
.expect("Couldn't get directory path")
.into();
unsafe {
SELECTED_DIRECTORY = Some(PathBuf::from(path));
}
}
// Invoke Android activity to pick a directory
let activity = native_activity();
let vm = activity.vm();
let _env = vm.attach_current_thread().unwrap();
let class_name = CString::new("com/example/myapp/DirectoryPickerActivity").unwrap();
let activity_class = _env.find_class(class_name.as_c_str()).unwrap();
let intent_method_id = _env
.get_method_id(activity_class, "startActivity", "()V")
.unwrap();
_env.call_method(activity_class, intent_method_id, "()V", &[])
.unwrap();
// Return the selected directory path or an error if not selected
unsafe {
match &SELECTED_DIRECTORY {
Some(path) => Ok(path.clone()),
None => Err(Error::from("No directory selected")),
}
}
}
#[cfg(not(target_os = "android"))]
fn select_directory_desktop() -> Result<PathBuf, Error> {
use rfd::FileDialog;
let selected_dir: Option<PathBuf> = FileDialog::new().set_directory(".").pick_folder();
match selected_dir {
Some(path) => Ok(path),
None => Err(Error::from("No directory selected")),
}
} Desktop Function works fine, I tested. But after I added
And if I use
There was overall 12 errors about |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Sounds like you didn't add the dependencies in a platform dependent way, could that be? It would look something like this [target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
rfd = "123"
[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]
ndk = "123" Also did you know about our dialog plugin? It should work on desktop and mobile now. |
Beta Was this translation helpful? Give feedback.
Sounds like you didn't add the dependencies in a platform dependent way, could that be? It would look something like this
Also did you know about our dialog plugin? It should work on desktop and mobile now.