Skip to content

Commit 8b47f7d

Browse files
author
zhaoyongqiang
committed
添加token验证
1 parent c5d00fd commit 8b47f7d

File tree

60 files changed

+1172
-220
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+1172
-220
lines changed

iOS/APIExample.xcodeproj/project.pbxproj

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,9 @@
127127
A7CA48C424553CF700507435 /* Popover.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A7CA48C224553CF600507435 /* Popover.storyboard */; };
128128
CBCDE23FB64E60D6A79F3723 /* Pods_Agora_ScreenShare_Extension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 09E72C5D1AABD812866E41A6 /* Pods_Agora_ScreenShare_Extension.framework */; };
129129
D4046B5D3DE984062E3F6D92 /* Pods_APIExample.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 07A781F5D5D3783CEC7C8EFA /* Pods_APIExample.framework */; };
130+
E74877DD28A3602400CA2F58 /* ToastView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74877DA28A3602400CA2F58 /* ToastView.swift */; };
131+
E74877DE28A3602400CA2F58 /* NetworkManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74877DB28A3602400CA2F58 /* NetworkManager.swift */; };
132+
E74877DF28A3602400CA2F58 /* JSONObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74877DC28A3602400CA2F58 /* JSONObject.swift */; };
130133
E763A87D288E977C00FE99FA /* Util.swift in Sources */ = {isa = PBXBuildFile; fileRef = E763A87C288E977C00FE99FA /* Util.swift */; };
131134
E789AAF928694D8C00851463 /* LocalAccess.strings in Resources */ = {isa = PBXBuildFile; fileRef = E789AAF428694D8C00851463 /* LocalAccess.strings */; };
132135
E789AAFA28694D8C00851463 /* LocalAccess.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E789AAF628694D8C00851463 /* LocalAccess.storyboard */; };
@@ -349,6 +352,9 @@
349352
A7847F932458089E00469187 /* AgoraExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AgoraExtension.swift; sourceTree = "<group>"; };
350353
A7BD765F247CC6920062A6B3 /* UITypeAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UITypeAlias.swift; sourceTree = "<group>"; };
351354
A7CA48C324553CF600507435 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Popover.storyboard; sourceTree = "<group>"; };
355+
E74877DA28A3602400CA2F58 /* ToastView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToastView.swift; sourceTree = "<group>"; };
356+
E74877DB28A3602400CA2F58 /* NetworkManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkManager.swift; sourceTree = "<group>"; };
357+
E74877DC28A3602400CA2F58 /* JSONObject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONObject.swift; sourceTree = "<group>"; };
352358
E763A87C288E977C00FE99FA /* Util.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Util.swift; sourceTree = "<group>"; };
353359
E789AAF528694D8C00851463 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/LocalAccess.strings"; sourceTree = "<group>"; };
354360
E789AAF728694D8C00851463 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LocalAccess.storyboard; sourceTree = "<group>"; };
@@ -761,6 +767,7 @@
761767
03D13BFF24488F1E00B599B3 /* Common */ = {
762768
isa = PBXGroup;
763769
children = (
770+
E74877D928A3602400CA2F58 /* NetworkManager */,
764771
67B8C7A128050EE200195106 /* Utils */,
765772
0364C1FF2551B19800C6C0AE /* ARKit */,
766773
0339BE73251EF728007D4FDD /* RtcChannelPublishPlugin */,
@@ -944,6 +951,16 @@
944951
name = "Supporting Files";
945952
sourceTree = "<group>";
946953
};
954+
E74877D928A3602400CA2F58 /* NetworkManager */ = {
955+
isa = PBXGroup;
956+
children = (
957+
E74877DA28A3602400CA2F58 /* ToastView.swift */,
958+
E74877DB28A3602400CA2F58 /* NetworkManager.swift */,
959+
E74877DC28A3602400CA2F58 /* JSONObject.swift */,
960+
);
961+
path = NetworkManager;
962+
sourceTree = "<group>";
963+
};
947964
E789AAF328694D8C00851463 /* LocalAccess */ = {
948965
isa = PBXGroup;
949966
children = (
@@ -1207,6 +1224,7 @@
12071224
036CBA47251990B400D74FAD /* AgoraCustomEncryption.h in Sources */,
12081225
670709A5282659B100A72FD6 /* SampleHandlerUtil.m in Sources */,
12091226
033A9EFF252D61E200BC26E1 /* CustomVideoSourceMediaIO.swift in Sources */,
1227+
E74877DF28A3602400CA2F58 /* JSONObject.swift in Sources */,
12101228
036CBA3F2519186300D74FAD /* StreamEncryption.swift in Sources */,
12111229
0339BE9625203293007D4FDD /* ScreenShare.swift in Sources */,
12121230
033A9F00252D61E200BC26E1 /* CustomAudioSource.swift in Sources */,
@@ -1239,6 +1257,7 @@
12391257
033A9EE5252D5C6900BC26E1 /* VideoMetadata.swift in Sources */,
12401258
8BAF3C9A2758693B0073B30E /* VideoProcess.swift in Sources */,
12411259
036C42BF24D5853200A59000 /* AgoraMediaRawData.m in Sources */,
1260+
E74877DE28A3602400CA2F58 /* NetworkManager.swift in Sources */,
12421261
036C42B024D2955D00A59000 /* AgoraCameraSourcePush.swift in Sources */,
12431262
0318857924CD667A00C699EB /* SettingsViewController.swift in Sources */,
12441263
F3184EFF27F85AD700FA402D /* AgoraPictureInPictureController.m in Sources */,
@@ -1247,6 +1266,7 @@
12471266
A7BD7660247CC6920062A6B3 /* UITypeAlias.swift in Sources */,
12481267
57B7FC83259C313200407BE1 /* RawAudioData.swift in Sources */,
12491268
03DF1D9124CFC29700DF7151 /* UIColor+CSRGB.m in Sources */,
1269+
E74877DD28A3602400CA2F58 /* ToastView.swift in Sources */,
12501270
0339BECC25210A93007D4FDD /* SuperResolution.swift in Sources */,
12511271
03D13C0124488F1F00B599B3 /* KeyCenter.swift in Sources */,
12521272
03BEED08251C35E7005E78F4 /* AudioMixing.swift in Sources */,

iOS/APIExample/Common/KeyCenter.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
//
88

99
struct KeyCenter {
10-
static let AppId: String = <#Your App Id#>
10+
static let AppId: String = <#YOUR APPID#>
1111

1212
// assign token to nil if you have not enabled app certificate
13-
static var Token: String? = <#Temp Access Token#>
13+
static let Certificate: String? = <#YOUR Certificate#>
14+
15+
static var Token: String? = nil
1416
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
//
2+
// JSONObject.swift
3+
// BreakoutRoom
4+
//
5+
// Created by zhaoyongqiang on 2021/11/2.
6+
//
7+
8+
import Foundation
9+
10+
class JSONObject {
11+
/// 字典转模型
12+
static func toModel<T: Codable>(_ type: T.Type, value: Any?) -> T? {
13+
guard let value = value else { return nil }
14+
return toModel(type, value: value)
15+
}
16+
/// 字典转模型
17+
static func toModel<T: Codable>(_ type: T.Type, value: Any) -> T? {
18+
guard let data = try? JSONSerialization.data(withJSONObject: value) else { return nil }
19+
let decoder = JSONDecoder()
20+
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")
21+
return try? decoder.decode(type, from: data)
22+
}
23+
/// JSON字符串转模型
24+
static func toModel<T: Codable>(_ type: T.Type, value: String?) -> T? {
25+
guard let value = value else { return nil }
26+
return toModel(type, value: value)
27+
}
28+
/// JSON字符串转模型
29+
static func toModel<T: Codable>(_ type: T.Type, value: String) -> T? {
30+
let decoder = JSONDecoder()
31+
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")
32+
guard let t = try? decoder.decode(T.self, from: value.data(using: .utf8)!) else { return nil }
33+
return t
34+
}
35+
/// 模型转JSON字符串
36+
static func toJson<T: Codable>(_ model: T) -> [String: Any] {
37+
let jsonString = toJsonString(model) ?? ""
38+
return toDictionary(jsonString: jsonString)
39+
}
40+
/// 模型转JSON数组字符串
41+
static func toJsonArray<T: Codable>(_ model: T) -> [[String: Any]]? {
42+
let jsonString = toJsonString(model) ?? ""
43+
return toArray(jsonString: jsonString)
44+
}
45+
/// 模型转JSON字符串
46+
static func toJsonString<T: Codable>(_ model: T) -> String? {
47+
let encoder = JSONEncoder()
48+
encoder.outputFormatting = .prettyPrinted
49+
guard let data = try? encoder.encode(model) else { return nil }
50+
return String(data: data, encoding: .utf8)
51+
}
52+
/// JSON字符串转字典
53+
static func toDictionary(jsonString: String) -> [String: Any] {
54+
guard let jsonData = jsonString.data(using: .utf8) else { return [:] }
55+
guard let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers), let result = dict as? [String: Any] else { return [:] }
56+
return result
57+
}
58+
/// JSON字符串转字典
59+
static func toDictionary(jsonStr: String) -> [String: String] {
60+
guard let jsonData = jsonStr.data(using: .utf8) else { return [:] }
61+
guard let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers), let result = dict as? [String: Any] else { return [:] }
62+
var data = [String: String]()
63+
for item in result {
64+
data[item.key] = "\(item.value)"
65+
}
66+
return data
67+
}
68+
/// JSON字符串转数组
69+
static func toArray(jsonString: String) -> [[String: Any]]? {
70+
guard let jsonData = jsonString.data(using: .utf8) else { return nil }
71+
guard let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers), let result = array as? [[String: Any]] else { return nil }
72+
return result
73+
}
74+
/// 字典转JSON字符串
75+
static func toJsonString(dict: [String: Any]?) -> String? {
76+
guard let dict = dict else { return nil }
77+
if (!JSONSerialization.isValidJSONObject(dict)) {
78+
print("字符串格式错误!")
79+
return nil
80+
}
81+
guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else { return nil }
82+
guard let jsonString = String(data: data, encoding: .utf8) else { return nil }
83+
return jsonString
84+
}
85+
/// 字典数组转JSON字符串
86+
static func toJsonString(array: [[String: Any]?]?) -> String? {
87+
guard let array = array else { return nil }
88+
var jsonString = "["
89+
var i = 0
90+
let count = array.count
91+
for dict in array {
92+
guard let dict = dict else { return nil }
93+
if (!JSONSerialization.isValidJSONObject(dict)) {
94+
print("字符串格式错误!")
95+
return nil
96+
}
97+
guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else { return nil }
98+
guard let tmp = String(data: data, encoding: .utf8) else { return nil }
99+
jsonString.append(tmp)
100+
if i < count - 1 {
101+
jsonString.append(",")
102+
}
103+
i = i + 1
104+
}
105+
jsonString.append("]")
106+
return jsonString
107+
}
108+
}
109+
110+
extension String {
111+
func toArray() -> [[String: Any]]? {
112+
JSONObject.toArray(jsonString: self)
113+
}
114+
func toDictionary() -> [String : String] {
115+
JSONObject.toDictionary(jsonStr: self)
116+
}
117+
}
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
//
2+
// NetworkManager.swift
3+
// Scene-Examples
4+
//
5+
// Created by zhaoyongqiang on 2021/11/19.
6+
//
7+
8+
import UIKit
9+
10+
class NetworkManager {
11+
enum HTTPMethods: String {
12+
case GET = "GET"
13+
case POST = "POST"
14+
}
15+
16+
typealias SuccessClosure = ([String: Any]) -> Void
17+
typealias FailClosure = (String) -> Void
18+
19+
private lazy var sessionConfig: URLSessionConfiguration = {
20+
let config = URLSessionConfiguration.default
21+
config.httpAdditionalHeaders = ["Content-Type": "application/json",
22+
"X-LC-Id": "fkUjxadPMmvYF3F3BI4uvmjo-gzGzoHsz",
23+
"X-LC-Key": "QAvFS62IOR28GfSFQO5ze45s",
24+
"X-LC-Session": "qmdj8pdidnmyzp0c7yqil91oc"]
25+
config.timeoutIntervalForRequest = 30
26+
config.timeoutIntervalForResource = 30
27+
config.requestCachePolicy = .reloadIgnoringLocalCacheData
28+
return config
29+
}()
30+
31+
static let shared = NetworkManager()
32+
private init() { }
33+
private let baseUrl = "https://test-toolbox.bj2.agoralab.co/v1/token/generate"
34+
35+
36+
func generateToken(channelName: String, uid: UInt = 0, success: @escaping () -> Void) {
37+
generateToken(channelName: channelName, uid: uid) { _ in
38+
success()
39+
}
40+
}
41+
42+
func generateToken(channelName: String, uid: UInt = 0, success: @escaping (String?) -> Void) {
43+
ToastView.showWait(text: "loading...", view: nil)
44+
if KeyCenter.Certificate == nil || KeyCenter.Certificate?.isEmpty == true {
45+
success(nil)
46+
ToastView.hidden()
47+
return
48+
}
49+
let params = ["appCertificate": KeyCenter.Certificate ?? "",
50+
"appId": KeyCenter.AppId,
51+
"channelName": channelName,
52+
"expire": 900,
53+
"src": "iOS",
54+
"ts": "".timeStamp,
55+
"type": 1,
56+
"uid": "\(uid)"] as [String : Any]
57+
NetworkManager.shared.postRequest(urlString: "https://test-toolbox.bj2.agoralab.co/v1/token/generate", params: params, success: { response in
58+
let data = response["data"] as? [String: String]
59+
let token = data?["token"]
60+
KeyCenter.Token = token
61+
print(response)
62+
success(token)
63+
ToastView.hidden(delay: 0.25)
64+
}, failure: { error in
65+
print(error)
66+
success(nil)
67+
ToastView.hidden(delay: 0.25)
68+
})
69+
}
70+
71+
func getRequest(urlString: String, success: SuccessClosure?, failure: FailClosure?) {
72+
DispatchQueue.global().async {
73+
self.request(urlString: urlString, params: nil, method: .GET, success: success, failure: failure)
74+
}
75+
}
76+
func postRequest(urlString: String, params: [String: Any]?, success: SuccessClosure?, failure: FailClosure?) {
77+
DispatchQueue.global().async {
78+
self.request(urlString: urlString, params: params, method: .POST, success: success, failure: failure)
79+
}
80+
}
81+
82+
private func request(urlString: String,
83+
params: [String: Any]?,
84+
method: HTTPMethods,
85+
success: SuccessClosure?,
86+
failure: FailClosure?) {
87+
let session = URLSession(configuration: sessionConfig)
88+
guard let request = getRequest(urlString: urlString,
89+
params: params,
90+
method: method,
91+
success: success,
92+
failure: failure) else { return }
93+
session.dataTask(with: request) { data, response, error in
94+
DispatchQueue.main.async {
95+
self.checkResponse(response: response, data: data, success: success, failure: failure)
96+
}
97+
}.resume()
98+
}
99+
100+
private func getRequest(urlString: String,
101+
params: [String: Any]?,
102+
method: HTTPMethods,
103+
success: SuccessClosure?,
104+
failure: FailClosure?) -> URLRequest? {
105+
106+
let string = urlString.hasPrefix("http") ? urlString : baseUrl.appending(urlString)
107+
guard let url = URL(string: string) else {
108+
return nil
109+
}
110+
var request = URLRequest(url: url)
111+
request.httpMethod = method.rawValue
112+
if method == .POST {
113+
request.httpBody = try? JSONSerialization.data(withJSONObject: params ?? [], options: .sortedKeys)//convertParams(params: params).data(using: .utf8)
114+
}
115+
let curl = request.cURL(pretty: true)
116+
debugPrint("curl == \(curl)")
117+
return request
118+
}
119+
120+
private func convertParams(params: [String: Any]?) -> String {
121+
guard let params = params else { return "" }
122+
let value = params.map({ String(format: "%@=%@", $0.key, "\($0.value)") }).joined(separator: "&")
123+
return value
124+
}
125+
126+
private func checkResponse(response: URLResponse?, data: Data?, success: SuccessClosure?, failure: FailClosure?) {
127+
if let httpResponse = response as? HTTPURLResponse {
128+
switch httpResponse.statusCode {
129+
case 200...201:
130+
if let resultData = data {
131+
let result = String(data: resultData, encoding: .utf8)
132+
print(result ?? "")
133+
success?(JSONObject.toDictionary(jsonString: result ?? ""))
134+
} else {
135+
failure?("Error in the request status code \(httpResponse.statusCode), response: \(String(describing: response))")
136+
}
137+
default:
138+
failure?("Error in the request status code \(httpResponse.statusCode), response: \(String(describing: response))")
139+
}
140+
}
141+
}
142+
}
143+
144+
extension URLRequest {
145+
public func cURL(pretty: Bool = false) -> String {
146+
let newLine = pretty ? "\\\n" : ""
147+
let method = (pretty ? "--request " : "-X ") + "\(httpMethod ?? "GET") \(newLine)"
148+
let url: String = (pretty ? "--url " : "") + "\'\(url?.absoluteString ?? "")\' \(newLine)"
149+
150+
var cURL = "curl "
151+
var header = ""
152+
var data: String = ""
153+
154+
if let httpHeaders = allHTTPHeaderFields, httpHeaders.keys.count > 0 {
155+
for (key,value) in httpHeaders {
156+
header += (pretty ? "--header " : "-H ") + "\'\(key): \(value)\' \(newLine)"
157+
}
158+
}
159+
160+
if let bodyData = httpBody, let bodyString = String(data: bodyData, encoding: .utf8), !bodyString.isEmpty {
161+
data = "--data '\(bodyString)'"
162+
}
163+
164+
cURL += method + url + header + data
165+
166+
return cURL
167+
}
168+
}
169+
170+
extension String {
171+
var timeStamp: String {
172+
let date = Date()
173+
let timeInterval = date.timeIntervalSince1970
174+
let millisecond = CLongLong(timeInterval * 1000)
175+
return "\(millisecond)"
176+
}
177+
}

0 commit comments

Comments
 (0)