ios - 如何在 Flutter 中读取已使用 iOS 中的 NSKeyedArchiver 写入文件系统的文件作为字符串?

标签 ios objective-c flutter dart nskeyedarchiver

使用在 Flutter 上编写的应用程序更新 iOS native 应用程序后,我想使用 iOS 设备上的文件系统读取文件 Dart 。我想要读取的文件之前已使用以下 ObjectiveC 代码写入文件系统:

- (void)setAccount:(FTAccountModel *)account {
    _account = account;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    path = [path stringByAppendingPathComponent:AccountModelPath];
    if (account) {
        NSArray * array = @[account];
        [array writeToFile:path atomically:YES];
        [NSKeyedArchiver archiveRootObject:array toFile:path];
    }
}

我在 Flutter 中使用 path_provider 尝试了以下方法封装:

final appDocDir = await getApplicationDocumentsDirectory();
final accountDataFile = File('${appDocDir.path}/$_iosAccountDataFile');
String contents = await accountDataFile.readAsString();
print("contents: $contents");

但是在调用 readAsString() 方法时出现错误:

FileSystemException: Failed to decode data using encoding 'utf-8', path = '/var/mobile/Containers/Data/Application/FBCB4862-E5EA-4C93-8C2E-3DF1F00A8645/Documents/AccountModel.data'

如何使用 DartFlutter 读取 iOS 设备上使用 NSKeyedArchiver 编写的文件?

最佳答案

在撰写此答案时,没有插件可以读取该文件,该文件之前已在 iOS 中使用 NSKeyedArchiver 写入文件系统。读取文件的方式是 write custom platform-specific code .

因此 Swift 上的 iOS 平台代码将类似于以下内容:

private func callGetUserIdFromNativeApp(result: @escaping FlutterResult) {
    var account: FTAccountModel?
    let fm = FileManager.default
    let urls = fm.urls(for: .documentDirectory, in: .userDomainMask)
    if (!urls.isEmpty) {
        let file = urls[0].appendingPathComponent("Accounts.data", isDirectory: false)
        
        if (fm.fileExists(atPath: file.path)) {
            if let accountArray: [FTAccountModel] = NSKeyedUnarchiver.unarchiveObject(withFile: file.path) as? [FTAccountModel] {
        
                if (!accountArray.isEmpty) {
                    account = accountArray[0]
                }
            }
        }
    }
    
    if let userId: Int = account?.userId {
        result(String(userId))
    } else {
        result(nil)
    }
}

flutter部分将使用MethodChannel调用原生代码:

static const MethodChannel _channel = const MethodChannel("CHANNEL_NAME");

static Future<String> getUserIdFromNativeIos() async {
  try {
    return await _channel.invokeMethod("METHOD_NAME");
  } catch (e){
    return _failedString();
  }
}

关于ios - 如何在 Flutter 中读取已使用 iOS 中的 NSKeyedArchiver 写入文件系统的文件作为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67125971/

相关文章:

ios - 从 firestore 下载一系列文档

ios - 使用核心 api 上传 DropBox 文件 https ://api-content. dropbox.com/1/files/<root>/<path>

user-interface - flutter ,按下按钮后如何复制文本?

Flutter - WebView webview_flutter 和 BottomNavigationBar 在 onTap 时不会刷新

使用 HttpClient 进行 Flutter Widget 测试

ios - 将数据发布到服务器时出现字母问题

ios - 在数组上使用 NSUserDefaults

ios - 用于视频流的 FFmpeg ios 示例代码

objective-c - iOS 6 中的 UIPopoverController 方向崩溃

iphone - 区分applicationDidEnterBackground和applicationWillTerminate