我正在使用类似的东西,我希望这会有所帮助
class NetworkingManager {
static let shared = NetworkingManager()
private init() {
sharedSession = enableCertificatePinning()
}
var sharedSession: Session?
func enableCertificatePinning() -> Session {
func getCertificates() -> [SecCertificate] {
let certs = ["AmazonExample1", "AmazonExample2"]
var certificates = [SecCertificate]()
certs.forEach { cert in
let url = Bundle.main.url(forResource: cert, withExtension: "cer")!
let localCertificate = try! Data(contentsOf: url) as CFData
if let certificate = SecCertificateCreateWithData(nil, localCertificate) {
certificates.append(certificate)
}
}
return certificates
}
let certificates: [SecCertificate] = getCertificates()
let trustPolicy = PinnedCertificatesTrustEvaluator(
certificates: certificates,
validateHost: true)
let trustPolicies = [certificateUrl: trustPolicy,
"https://example.com": trustPolicy,
"https://example2.com": trustPolicy]
let policyManager = ServerTrustManager(evaluators: trustPolicies)
return Session(
configuration: .default,
serverTrustManager: policyManager)
}
}
你可以这样使用
func exampleRequisiton(someBody: exampleBody, completion: @escaping (Result<responseExample, NetworkErrors>, _ message: String?) -> Void){
guard let url = URL(string: InviteUrl) else {
completion(.failure(.invalidUrl), nil)
return
}
var request = getDefaultRequest(url, .post)
request.httpBody = try? JSONEncoder().encode(someBody)
NetworkingManager.shared.sharedSession?.request(request).validate().responseDecodable(of: DefaultResponse.self, decoder: defaultDecoder) { data in
switch data.result {
case let .success(data):
completion(.success(data), nil)
case let .failure(error):
completion(.failure(.genericError), nil)
}
}
}
我尝试使用一个示例,其中包含申请(正文,标题)中使用的所有选项,因为我认为您需要在某些时候使用它。下面的代码是我单独创建的每个申请中使用的那些对象
var HttpHeaders: HTTPHeaders {
let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
return [
"SomeHeader if you have": "example"
]
}
func getDefaultRequest(_ url:URL, _ method:HTTPMethod) -> URLRequest{
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = method.rawValue
request.headers = HttpHeaders
return request
}
enum NetworkErrors: Error {
case authError
case genericError
case invalidUrl
case serverMessage
}
struct responseExample:Codable{
let systemTimeMillis: Int?
let message: String?
let status: Int?
}
struct exampleBody: Codable {
var example: String
}