You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin iOS 无法读取iCloud文件,GetDirectoryContent无返回值求助

Xamarin iOS iCloud存储文件查询无结果修复方案

核心问题原因

你当前直接枚举iCloud容器本地路径的逻辑仅能获取已同步到本地沙盒的文件,云端存在但未完成本地同步的文件无法通过GetDirectoryContent、GetEnumerator这类本地文件查询接口返回。

修复步骤

  • 确认项目配置无误:已开启iCloud功能、勾选iCloud Documents选项、配置的容器ID与你上传文件使用的iCloud容器ID完全匹配;模拟器测试时需登录有效iCloud账号且开启iCloud Drive同步
  • 替换本地路径枚举逻辑,改用NSMetadataQuery查询全量iCloud文件(覆盖云端、本地两种状态的文件)
  • 若需要访问文件内容,先触发云端文件的本地下载操作

修正后示例代码

// 定义全局的NSMetadataQuery对象,避免被GC回收导致查询中断
private NSMetadataQuery _iCloudQuery;

public void QueryiCloudFiles()
{
    var uburl = NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null)?.Append("Documents", true);
    if (uburl == null)
    {
        Console.WriteLine("iCloud容器不可用");
        return;
    }

    _iCloudQuery = new NSMetadataQuery();
    // 设置查询范围为iCloud Documents目录
    _iCloudQuery.SearchScopes = new NSObject[] { uburl };
    // 设置查询的文件类型,这里匹配所有文件,可按需调整
    _iCloudQuery.Predicate = NSPredicate.FromValue(true);

    // 注册查询完成通知
    NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.FinishedGatheringNotification, OnQueryFinished, _iCloudQuery);
    // 启动查询
    _iCloudQuery.StartQuery();
}

private void OnQueryFinished(NSNotification notification)
{
    _iCloudQuery.StopQuery();
    NSNotificationCenter.DefaultCenter.RemoveObserver(this, NSMetadataQuery.FinishedGatheringNotification, _iCloudQuery);

    foreach (NSMetadataItem item in _iCloudQuery.Results)
    {
        var fileName = item.ValueForAttribute(NSMetadataItem.FSNameKey) as NSString;
        var fileUrl = item.ValueForAttribute(NSMetadataItem.UrlKey) as NSUrl;
        var isDownloaded = (NSNumber)item.ValueForAttribute(NSMetadataItem.UbiquitousItemIsDownloadedKey);

        Console.WriteLine($"iCloud文件:{fileName},是否已下载:{isDownloaded.BoolValue}");

        // 如果文件未下载,触发下载操作
        if (!isDownloaded.BoolValue)
        {
            NSError downloadErr;
            NSFileManager.DefaultManager.StartDownloadingUbiquitousItem(fileUrl, out downloadErr);
            if (downloadErr != null)
            {
                Console.WriteLine($"下载失败:{downloadErr.LocalizedDescription}");
            }
        }
    }
}

额外优化点

调用NSFileManager的文件操作接口时,尽量直接传递NSUrl对象,不要转为字符串路径使用,避免路径转义异常导致查询失败。

内容的提问来源于stack exchange,提问作者Tulasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:39:02