forked from Feynmen/UnityHttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cookies.cs
109 lines (99 loc) · 2.91 KB
/
Cookies.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using UnityEngine;
using UnityEngine.Networking;
namespace UnityHTTP
{
public sealed class Cookies
{
private static Cookies _instance;
public static Cookies Instance
{
get
{
if (_instance == null)
{
_instance = new Cookies();
}
return _instance;
}
}
#if UNITY_IPHONE
//iOSCoockieStorageHelper.mm
[DllImport("__Internal")]
private static extern void ClearIOSCookieByValue(string cookie);
//iOSCoockieStorageHelper.mm
[DllImport("__Internal")]
private static extern void ClearAllIOSCookies();
#endif
private const string COOKIE = "Cookie";
private const string SET_COOKIE = "SET-COOKIE";
private string _cookieFullString;
public bool IsCookieExist { get { return PlayerPrefs.HasKey(COOKIE); } }
public void CheckRequestForSetCookie(UnityWebRequest request, bool isSaveCookie = true)
{
var cookie = request.GetResponseHeader(SET_COOKIE);
if (!string.IsNullOrEmpty(cookie))
{
ClearCookie();
if (isSaveCookie)
{
PlayerPrefs.SetString(COOKIE, cookie);
}
_cookieFullString = cookie;
}
}
public bool TrySetCookieInRequest(UnityWebRequest request)
{
if (!string.IsNullOrEmpty(_cookieFullString) || TryGetSavedCookie(out _cookieFullString))
{
request.SetRequestHeader(COOKIE, _cookieFullString);
return true;
}
return false;
}
public void ClearCookie()
{
if (IsCookieExist)
{
PlayerPrefs.DeleteKey(COOKIE);
}
if (!string.IsNullOrEmpty(_cookieFullString))
{
ClearCookieByValue(_cookieFullString);
_cookieFullString = null;
}
else //Warning! Maybe on iOS version lower than 10 could remove all device cookie
{
ClearAllCookies();
}
}
private bool TryGetSavedCookie(out string cookie)
{
cookie = string.Empty;
if (IsCookieExist)
{
cookie = PlayerPrefs.GetString(COOKIE);
return true;
}
return false;
}
private void ClearAllCookies()
{
#if UNITY_IPHONE
ClearAllIOSCookies();
#endif
}
private void ClearCookieByValue(string cookie)
{
#if UNITY_IPHONE
if (cookie.IndexOf(";", StringComparison.Ordinal) > 0)
{
ClearIOSCookieByValue(cookie);
}
else
{
ClearAllIOSCookies();
}
#endif
}
}
}