Как получить путь к файлу в приложении iOS, созданном в Unity?IOS

Программируем под IOS
Ответить
Anonymous
 Как получить путь к файлу в приложении iOS, созданном в Unity?

Сообщение Anonymous »

Я хотел бы получить пути к файлам в приложении iOS, разработанном с помощью Unity.
Поместите следующий исходный код в Assets/Plugins/iOS.
FileSelector.mm

Код: Выделить всё

#import 
#import 
#import "UnityInterface.h"

@interface FileSelectorDelegate : NSObject 
@end

@implementation FileSelectorDelegate
{
NSString* selectedFilePath;
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray *)urls
{
NSURL *url = [urls firstObject];
if (url)
{
BOOL securityScoped = [url startAccessingSecurityScopedResource];

if (securityScoped)
{
selectedFilePath = [url path];
UnitySendMessage("FileSelector", "SetSelectedFilePath", [selectedFilePath UTF8String]);
[url stopAccessingSecurityScopedResource];
}
else
{
NSLog(@"Failed to start accessing security scoped resource.");
}
}
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
{
NSLog(@"Document picker was cancelled.");
}

@end

extern "C" void _openFileDialog()
{
FileSelectorDelegate *delegate = [[FileSelectorDelegate alloc] init];
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
documentPicker.delegate = delegate;
documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
UIViewController *viewController = UnityGetGLViewController();
[viewController presentViewController:documentPicker animated:YES completion:nil];
}
Поместите следующий исходный код в Assets/Scripts.
FileSelector.cs

Код: Выделить всё

using UnityEngine;
using System.Runtime.InteropServices;
using TMPro;

public class FileSelector : MonoBehaviour
{
public TMP_Text tmp;
[DllImport("__Internal")]
private static extern void _openFileDialog();

private string selectedFilePath;

// Method to assign to On Click event of UI button
public void selectFile()
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
_openFileDialog();
}
else
{
Debug.Log("File dialog is only supported on iOS.");
}
}

// Method called from the native side
public void SetSelectedFilePath(string path)
{
selectedFilePath = path;
tmp.text = "Selected file path: " + selectedFilePath;
Debug.Log("Selected file path: " + selectedFilePath);
}

// Method to retrieve the selected file path
public string GetSelectedFilePath()
{
return selectedFilePath;
}
}
В Инспекторе добавьте кнопку для открытия диалогового окна файла на экране и компонент TMP_Text для отображения пути к выбранному файлу.
Выберите iOS в качестве платформы и приступайте к сборке.
Создайте выходной файл проекта и запустите его на iOS.
Выбранный файл представляет собой текстовый файл. файл вручную скопирован из Finder в папку приложения в приложении «Файл».
При нажатии кнопки загрузки на устройстве на экране ничего не появляется, а в консоли Xcode появляется следующее сообщение.

Не удалось связать миниатюры для выбранного URL-адреса.
file:///private/var/mobile/Containers/Data/Application/xxxx-xxxx- xxxx-xxxx-xxxx/Documents/Bea.vrl
с копией папки «Входящие»
файл:///private/var/mobile/Containers/Data/Application/xxxx-xxxx-xxxx-xxxx-xxxx/ tmp/com.atinde.xrlite-Inbox/Bea.vrl:
Error Domain=QLThumbnailErrorDomain Code=102 "(null)"
UserInfo={NSUnderlyingError=0x301cde340 {Error
Domain=GSLibraryErrorDomain Code =3 «Поколение не найдено»
UserInfo={NSDescription=Поколение не найдено}}}

Не могли бы вы сообщить нам, если они есть есть вопросы?
Заранее спасибо.

Подробнее здесь: https://stackoverflow.com/questions/786 ... t-in-unity
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»