This repository has been archived by the owner on Sep 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 135
/
CapacitorUrlRequest.swift
152 lines (125 loc) · 6.13 KB
/
CapacitorUrlRequest.swift
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import Foundation
import Capacitor
public class CapacitorUrlRequest: NSObject, URLSessionTaskDelegate {
private var request: URLRequest;
private var headers: [String:String];
enum CapacitorUrlRequestError: Error {
case serializationError(String?)
}
init(_ url: URL, method: String) {
request = URLRequest(url: url)
request.httpMethod = method
headers = [:]
if let lang = Locale.autoupdatingCurrent.languageCode {
if let country = Locale.autoupdatingCurrent.regionCode {
headers["Accept-Language"] = "\(lang)-\(country),\(lang);q=0.5"
} else {
headers["Accept-Language"] = "\(lang);q=0.5"
}
request.addValue(headers["Accept-Language"]!, forHTTPHeaderField: "Accept-Language")
}
}
private func getRequestDataAsJson(_ data: JSValue) throws -> Data? {
// We need to check if the JSON is valid before attempting to serialize, as JSONSerialization.data will not throw an exception that can be caught, and will cause the application to crash if it fails.
if JSONSerialization.isValidJSONObject(data) {
return try JSONSerialization.data(withJSONObject: data)
} else {
throw CapacitorUrlRequest.CapacitorUrlRequestError.serializationError("[ data ] argument for request of content-type [ application/json ] must be serializable to JSON")
}
}
private func getRequestDataAsFormUrlEncoded(_ data: JSValue) throws -> Data? {
guard var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false) else { return nil }
components.queryItems = []
guard let obj = data as? JSObject else {
// Throw, other data types explicitly not supported
throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ multipart/form-data ] may only be a plain javascript object")
}
obj.keys.forEach { (key: String) in
components.queryItems?.append(URLQueryItem(name: key, value: "\(obj[key] ?? "")"))
}
if components.query != nil {
return Data(components.query!.utf8)
}
return nil
}
private func getRequestDataAsMultipartFormData(_ data: JSValue) throws -> Data {
guard let obj = data as? JSObject else {
// Throw, other data types explicitly not supported.
throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ application/x-www-form-urlencoded ] may only be a plain javascript object")
}
let strings: [String: String] = obj.compactMapValues { any in
any as? String
}
var data = Data()
let boundary = UUID().uuidString
let contentType = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
headers["Content-Type"] = contentType
strings.forEach { key, value in
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
data.append(value.data(using: .utf8)!)
}
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
return data
}
private func getRequestDataAsString(_ data: JSValue) throws -> Data {
guard let stringData = data as? String else {
throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed as string")
}
return Data(stringData.utf8)
}
func getRequestHeader(_ index: String) -> Any? {
var normalized = [:] as [String:Any]
self.headers.keys.forEach { (key: String) in
normalized[key.lowercased()] = self.headers[key]
}
return normalized[index.lowercased()]
}
func getRequestData(_ body: JSValue, _ contentType: String) throws -> Data? {
// If data can be parsed directly as a string, return that without processing.
if let strVal = try? getRequestDataAsString(body) {
return strVal
} else if contentType.contains("application/json") {
return try getRequestDataAsJson(body)
} else if contentType.contains("application/x-www-form-urlencoded") {
return try getRequestDataAsFormUrlEncoded(body)
} else if contentType.contains("multipart/form-data") {
return try getRequestDataAsMultipartFormData(body)
} else {
throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed for content type [ \(contentType) ]")
}
}
public func setRequestHeaders(_ headers: [String: String]) {
headers.keys.forEach { (key: String) in
let value = headers[key]
request.addValue(value!, forHTTPHeaderField: key)
self.headers[key] = value
}
}
public func setRequestBody(_ body: JSValue) throws {
let contentType = self.getRequestHeader("Content-Type") as? String
if contentType != nil {
request.httpBody = try getRequestData(body, contentType!)
}
}
public func setContentType(_ data: String?) {
request.setValue(data, forHTTPHeaderField: "Content-Type")
}
public func setTimeout(_ timeout: TimeInterval) {
request.timeoutInterval = timeout;
}
public func getUrlRequest() -> URLRequest {
return request;
}
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(nil)
}
public func getUrlSession(_ call: CAPPluginCall) -> URLSession {
let disableRedirects = call.getBool("disableRedirects") ?? false
if (!disableRedirects) {
return URLSession.shared
}
return URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
}