Hi
I am very new to swift.
What I have tried till now is
import UIKit
import Foundation
import Security
// Custom URLSessionDelegate
class SSLPinningDelegate: NSObject, URLSessionDelegate {
let certificate: SecCertificate
let privateKey: SecKey
init(certificate: SecCertificate, privateKey: SecKey) {
self.certificate = certificate
self.privateKey = privateKey
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
let credential = URLCredential(identity: privateKey as! SecIdentity, certificates: [certificate], persistence: .forSession)
completionHandler(.useCredential, credential)
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
@objc(AzureProvisionWithCertificate)
class AzureProvisionWithCertificate: NSObject {
@objc(provisionAndUploadFile:withRegistrationId:withKey:withCertificate:withProvisionHost:withFileNameWithFolder:withModelId:withResolver:withRejecter:)
func provisionAndUploadFile(scopeId:String, registrationId:String, key:String, certificate:String, provisionHost:String, fileNameWithFolder:String, modelId:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void {
print("started: provisionAndUploadFile api")
// Create a session with the SSLPinningDelegate
let sslPinningDelegate = SSLPinningDelegate(certificate: certificate as! SecCertificate, privateKey: key as! SecKey)
print("sslPinningDelegate: \(sslPinningDelegate)")
// Create the URL
let url = URL(string: "https://global.azure-devices-provisioning.net/\(scopeId)/registrations/\(registrationId)/register?api-version=2021-06-01")!
// Create the request
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("utf-8", forHTTPHeaderField: "Content-Encoding")
// Create the request body
let bodyData = ["registrationId": registrationId]
let jsonData = try? JSONSerialization.data(withJSONObject: bodyData)
// Set the request body
request.httpBody = jsonData
// Create the session configuration
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
// Create the data task
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error: \(error.localizedDescription)")
reject("Error", error.localizedDescription, error)
} else if let data = data {
// Process the response data
let responseString = String(data: data, encoding: .utf8)
print("Response data: \(responseString)")
resolve("Response data: \(responseString)")
} else {
print("No data received")
reject("Error", "No data received", nil)
}
}
// Start the data task
task.resume()
}
}
Please help me to correct it.
Topic:
App & System Services
SubTopic:
Networking