其他分享
首页 > 其他分享> > 【ShareSDK】Unity使用ShareSDK实现新浪微博登录

【ShareSDK】Unity使用ShareSDK实现新浪微博登录

作者:互联网

准备工作

前文:ShareSDK获取新浪微博登录设置

导入ShareSDK插件

首先,先设置公司名,项目名

设置包名

与新浪微博添加的应用的包名保持一致

 

在Player Settings--Publishing Settings设置Keystore,

选择ShareSDK压缩包里面的demokey.keystore即可,也可以自己制作keystore

密码都是123456

 

将ShareSDK挂着一个物体上,填好相关信息

项目目录

 

在ShareSDKManager中实现初始化

public class ShareSDKManager : MonoBehaviour
{
    /// <summary>
    /// 单例模式
    /// </summary>
    public static ShareSDKManager Instance { get; private set; }

    public ShareSDK shareSDK;

    void Start()
    {
        Instance = this;

        DontDestroyOnLoad(gameObject);

        shareSDK = GetComponent<ShareSDK>();

        SceneManager.LoadScene("Login");
    }
}

新建工具类,方便调用


public static class Utility
{
    /// <summary>
    /// 写入文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="name">文件名称</param>
    /// <param name="info">信息</param>
    public static void WriteFile(string path, string name, string info)
    {
        StreamWriter sw;
        FileInfo fi = new FileInfo(path + "/" + name);
        sw = fi.CreateText();
        sw.WriteLine(info);
        sw.Close();
        sw.Dispose();
    }

    /// <summary>
    /// 读取文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="name">文件名称</param>
    /// <returns></returns>
    public static string ReadFile(string path, string name)
    {
        StreamReader sr;
        FileInfo fi = new FileInfo(path + "/" + name);
        sr = fi.OpenText();
        string info = sr.ReadToEnd();
        sr.Close();
        sr.Dispose();
        return info;
    }

    /// <summary>
    /// 吐司
    /// C#调用java代码,实现Android吐司
    /// </summary>
    /// <param name="info"></param>
    public static void MakeToast(string info)
    {
        AndroidJavaObject currentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaClass Toast = new AndroidJavaClass("android.widget.Toast");
        currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
        {
            Toast.CallStatic<AndroidJavaObject>("makeText", currentActivity, info, Toast.GetStatic<int>("LENGTH_LONG")).Call("show");
        }));
    }

    /// <summary>
    /// 转汉字
    /// </summary>
    /// <param name="unicode"></param>
    /// <returns></returns>
    public static string UnicodeToString(string unicode)
    {
        Regex reg = new Regex(@"(?!)\\[uU]([0-9a-f]{4})");
        return reg.Replace(unicode, delegate (Match m)
        {
            return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
        });

    }
}

Login场景

Login脚本,授权登录


public class Login : MonoBehaviour
{

    ShareSDK shareSDK;
    public Button buttonSinaWeiboAuth;

    void Start()
    {
        shareSDK = ShareSDKManager.Instance.shareSDK;

        //点击授权
        buttonSinaWeiboAuth.onClick.AddListener(onBSinaLoginuttonClickHandler);
        //授权回调
        shareSDK.authHandler = OnAuthResultHander;

    }

    /// <summary>
    /// 新浪微博登录按钮授权事件
    /// </summary>
    void onBSinaLoginuttonClickHandler()
    {
        if (shareSDK.IsAuthorized(PlatformType.SinaWeibo))
        {
            Utility.WriteFile(Application.persistentDataPath, "AuthInfo.dat", shareSDK.GetAuthInfo(PlatformType.SinaWeibo).toJson());

            Utility.MakeToast("已经授权," + shareSDK.GetAuthInfo(PlatformType.SinaWeibo)["userName"] + "登录成功");

            SceneManager.LoadScene("SinaWeibo");
        }
        else
        {
            shareSDK.Authorize(PlatformType.SinaWeibo);
        }
    }

    /// <summary>
    /// 授权结果回调事件
    /// </summary>
    /// <param name="reqID"></param>
    /// <param name="state"></param>
    /// <param name="type"></param>
    /// <param name="data"></param>
    void OnAuthResultHander(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {

        if (state == ResponseState.Success)
        {
            Utility.WriteFile(Application.persistentDataPath, "AuthInfo.dat", shareSDK.GetAuthInfo(PlatformType.SinaWeibo).toJson());

            Utility.MakeToast(shareSDK.GetAuthInfo(PlatformType.SinaWeibo)["userName"] + "登录成功");

            SceneManager.LoadScene("SinaWeibo");
        }
        else if (state == ResponseState.Fail)
        {
            Utility.MakeToast("登录失败");
        }
        if (state == ResponseState.Cancel)
        {
            Utility.MakeToast("登录被取消");
        }
    }
}

SinaWeibo场景

SinaWeibo脚本实现信息显示

public class SinaWeibo : MonoBehaviour
{

    ShareSDK shareSDK;

    public Image userIcon;//用户头像
    public Text userName;//用户昵称
    public Text userID;//用户ID
    public Image coverImage;//背景
    public Text attentionCount;//关注人数
    public Text fanCount;//粉丝人数
    public Text description;//描述

    PlatformType platformType;

    void Start()
    {
        try
        {
            shareSDK = ShareSDKManager.Instance.shareSDK;

            Hashtable authInfo = Utility.ReadFile(Application.persistentDataPath, "AuthInfo.dat").hashtableFromJson();

            StartCoroutine(LoadImage_userIcon(authInfo["userIcon"].ToString()));

            userName.text = authInfo["userName"].ToString();
            userID.text = authInfo["userID"].ToString();

            //获取用户信息
            shareSDK.GetUserInfo(PlatformType.SinaWeibo);
            //获取用户信息回调
            shareSDK.showUserHandler = OnGetUserInfoResultHandler;

            //获取好友列表
            shareSDK.GetFriendList(PlatformType.SinaWeibo, 15, 0);
            //获取好友列表回调
            shareSDK.getFriendsHandler = OnGetFriendResultHandler;
        }
        catch (Exception ex)
        {
            Utility.MakeToast("start " + ex.ToString());
            Utility.WriteFile(Application.persistentDataPath, "Log.log", ex.ToString());
        }
    }

    #region 获取用户信息
    /// <summary>
    /// 获取用户信息结果回调事件
    /// </summary>
    /// <param name="reqID"></param>
    /// <param name="state"></param>
    /// <param name="type"></param>
    /// <param name="data"></param>
    void OnGetUserInfoResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {
        try
        {
            Utility.MakeToast(state.ToString());

            if (state == ResponseState.Begin)
            {
                Utility.MakeToast("开始获取用户信息");
            }
            else if (state == ResponseState.Success)
            {
                //Utility.MakeToast("获取用户信息成功");
                //存储用户信息
                Utility.WriteFile(Application.persistentDataPath, "UserInfo.dat", data.toJson());

                StartCoroutine(LoadImage_coverImage(data["cover_image_phone"].ToString()));

                description.text = data["description"].ToString();
            }
            else if (state == ResponseState.Fail)
            {
                Utility.MakeToast("获取用户信息失败");
            }
            if (state == ResponseState.Cancel)
            {
                Utility.MakeToast("获取用户信息时被取消");
            }
        }
        catch (Exception ex)
        {
            Utility.MakeToast(ex.ToString());
            Utility.WriteFile(Application.persistentDataPath, "Log2.log", ex.ToString());
        }
    }

    #region 获取图片

    /// <summary>
    /// 获取背景图片
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator LoadImage_coverImage(string url)
    {
        if (url != string.Empty)
        { yield return null; }

        UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
        yield return request.SendWebRequest();

        Texture2D texture2D = DownloadHandlerTexture.GetContent(request);
        coverImage.sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
    }

    /// <summary>
    /// 获取头像
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator LoadImage_userIcon(string url)
    {
        if (url != string.Empty)
        { yield return null; }

        UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
        yield return request.SendWebRequest();

        Texture2D texture2D = DownloadHandlerTexture.GetContent(request);
        userIcon.sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);

    }
    #endregion

    #endregion

    #region  获取好友信息
    /// <summary>
    /// 获取好友列表
    /// </summary>
    /// <param name="reqID"></param>
    /// <param name="state"></param>
    /// <param name="type"></param>
    /// <param name="data"></param>
    void OnGetFriendResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {
        try
        {
            if (state == ResponseState.Begin)
            {
                Utility.MakeToast("开始获取好友信息");
            }
            else if (state == ResponseState.Success)
            {
                Utility.MakeToast("获取好友信息成功");
                //存储用户信息
                Utility.WriteFile(Application.persistentDataPath, "FriendList.dat", data.toJson());
                Hashtable friendList = Utility.ReadFile(Application.persistentDataPath, "FriendList.dat").hashtableFromJson();

                attentionCount.text = friendList["total_number"].ToString();
            }
            else if (state == ResponseState.Fail)
            {
                Utility.MakeToast("获取好友信息失败");
            }
            if (state == ResponseState.Cancel)
            {
                Utility.MakeToast("获取好友信息时被取消");
            }
        }
        catch (Exception ex)
        {
            Utility.MakeToast(ex.ToString());
            Utility.WriteFile(Application.persistentDataPath, "Log3.log", ex.ToString());
        }
    }
    #endregion

    public void OnSignOutButtonClick()
    {
        shareSDK.CancelAuthorize(PlatformType.SinaWeibo);
        SceneManager.LoadScene("Login");
    }

}

发布到安卓后,授权登录

效果,

由于获取太多次,有些数据获取不全,获取的Json为空

 

 

 

 

 

 

标签:string,MakeToast,state,ShareSDK,Unity,微博,shareSDK,public,Utility
来源: https://blog.csdn.net/weixin_38211198/article/details/89769915