You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Unity3d开发iOS容器应用:GitHub登录及文件访问功能求助

Unity iOS容器应用实现GitHub登录、文件列表查看与下载方案

嘿,我刚好折腾过Unity iOS集成GitHub的类似需求,结合你已经有GitHub App的client_id和client_secret,给你梳理一套能跑通的方案,一步步来:

一、GitHub OAuth2登录流程

因为是iOS容器应用,我们可以结合Unity的深层链接(Deep Link)来完成授权流程,不用依赖太多原生插件:

  1. 构造授权跳转URL
    先在GitHub App后台配置好重定向URI(比如yourapp://github-auth,记得和Unity里的URL Scheme对应),然后构造授权链接:
string clientId = "你的client_id";
string redirectUri = "yourapp://github-auth";
string authUrl = $"https://github.com/login/oauth/authorize?client_id={clientId}&redirect_uri={redirectUri}&scope=repo";
// 打开授权页面
Application.OpenURL(authUrl);
  1. 捕获授权回调并换取Access Token
    在Unity里监听深层链接激活事件,拿到授权码后去换token:
private void OnEnable()
{
    Application.deepLinkActivated += HandleDeepLink;
}

private void HandleDeepLink(string url)
{
    var uri = new Uri(url);
    var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);
    string authCode = queryParams["code"];
    if (!string.IsNullOrEmpty(authCode))
    {
        StartCoroutine(ExchangeCodeForToken(authCode));
    }
}

IEnumerator ExchangeCodeForToken(string code)
{
    string tokenUrl = "https://github.com/login/oauth/access_token";
    WWWForm form = new WWWForm();
    form.AddField("client_id", "你的client_id");
    form.AddField("client_secret", "你的client_secret");
    form.AddField("code", code);
    form.AddField("redirect_uri", "yourapp://github-auth");

    using (UnityWebRequest request = UnityWebRequest.Post(tokenUrl, form))
    {
        request.SetRequestHeader("Accept", "application/json");
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            var tokenResponse = JsonUtility.FromJson<GitHubToken>(request.downloadHandler.text);
            string accessToken = tokenResponse.access_token;
            // 把token存起来,比如用PlayerPrefs或者iOS Keychain(更安全)
            Debug.Log("拿到Token:" + accessToken);
        }
        else
        {
            Debug.LogError("换Token失败:" + request.error);
        }
    }
}

// 序列化Token响应模型
[System.Serializable]
private class GitHubToken
{
    public string access_token;
    public string token_type;
    public string scope;
}
  1. iOS URL Scheme配置
    打开Unity的Player Settings → iOS → Other Settings → Configuration,在URL Schemes里添加yourapp(和你重定向URI的scheme一致),这样授权完成后才能跳回你的应用。

二、获取仓库图片文件列表

用GitHub REST API拉取指定仓库的文件,筛选出图片类型:

IEnumerator FetchImageFiles(string owner, string repo, string folderPath, string accessToken)
{
    string apiUrl = $"https://api.github.com/repos/{owner}/{repo}/contents/{folderPath}";
    using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
    {
        request.SetRequestHeader("Authorization", $"token {accessToken}");
        request.SetRequestHeader("User-Agent", "Unity-iOS-GitHub-App"); // GitHub API必须带这个头
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            var fileList = JsonUtility.FromJson<GitHubFile[]>(request.downloadHandler.text);
            foreach (var file in fileList)
            {
                if (file.type == "file" && IsImageFile(file.name))
                {
                    // 这里可以把文件信息传给UI展示,比如文件名、下载链接
                    Debug.Log("找到图片:" + file.name + ",下载链接:" + file.download_url);
                }
            }
        }
        else
        {
            Debug.LogError("拉取文件列表失败:" + request.error);
        }
    }
}

// 判断是否为图片文件
private bool IsImageFile(string fileName)
{
    string[] imageExts = { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    return imageExts.Contains(ext);
}

// 序列化文件模型
[System.Serializable]
private class GitHubFile
{
    public string name;
    public string path;
    public string type;
    public string download_url;
}

三、下载图片到iOS本地

用UnityWebRequest下载图片,保存到iOS沙盒的持久化路径:

IEnumerator DownloadAndSaveImage(string downloadUrl, string fileName, string accessToken)
{
    using (UnityWebRequest request = UnityWebRequest.Get(downloadUrl))
    {
        // 私有仓库需要带Token,公开仓库可以去掉这行
        request.SetRequestHeader("Authorization", $"token {accessToken}");
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            // iOS持久化路径,文件会被保留,用户可以通过应用文件共享访问(需要开启)
            string savePath = System.IO.Path.Combine(Application.persistentDataPath, fileName);
            System.IO.File.WriteAllBytes(savePath, request.downloadHandler.data);
            Debug.Log("图片保存成功:" + savePath);
            // 这里可以触发UI更新,比如显示下载好的图片
        }
        else
        {
            Debug.LogError("下载图片失败:" + request.error);
        }
    }
}

几个关键注意点

  • 权限配置:确保你的GitHub App申请了repo权限(访问私有仓库)或public_repo(仅访问公开仓库),不然API会返回权限错误。
  • Token安全:尽量不要把client_secret硬编码在Unity代码里,最好用自己的后端服务中转Token交换流程,避免密钥暴露。如果没后端,打包时记得代码混淆,降低风险。
  • ATS配置:iOS默认禁止非HTTPS请求,GitHub API都是HTTPS,所以没问题;如果遇到奇怪的网络错误,可以在Info.plist里添加ATS例外(不过苹果不推荐,尽量不用)。

内容的提问来源于stack exchange,提问作者sama.van

火山引擎 最新活动