I am trying to call my api in my home network but for some reason, I get the following error message:
finished with error [-1202] Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.179.185” which could put your confidential information at risk."
I tried some solutions but none of them is fitting my code somehow.
import SwiftUI
import EFQRCode
struct ShowQRCodeView: View {
//@Binding var isLoggedIn : Bool
@Binding var deviceId : String
@Binding var apiKey : String
@Binding var userId : String
@Binding var employeeId : Int
@State private var x = UUID().uuidString
@State var users = [User]()
var body: some View {
VStack(){
Form{
Section("QR-Code"){
if let cgImage = EFQRCode.generate(for: deviceId) {
Image(uiImage: UIImage(cgImage: cgImage)).resizable().frame(width: 150, height: 150)
}
Button("Login"){
Task{
await doHTTPUserCall()
}
}
}
}.frame(height: 180)
}.onAppear {
if (deviceId == "") {
deviceId = x // Could change here
}
}
}
func doHTTPUserCall() async {
var url = "https://192.168.179.185:8090/CC0001/BE/admin/api/v1/employee/deviceid/"
url = String(deviceId)
guard let reqUrl = URL(string: url) else {
print("Invalid URL")
return()
}
var req = URLRequest(url: reqUrl)
req.httpMethod = "GET"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone(abbreviation: "ETC")
let task = URLSession.shared.dataTask(with: req) { data, response, error in
if let data = data {
do{
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
users = try decoder.decode(Array<User>.self, from: data)
} catch{
print(error)
}
} else if let error = error {
print("HTTP Request Failed \(error)")
}
if let response = response as? HTTPURLResponse {
print("Response HTTP Status code: \(response.statusCode)")
}
}
task.resume()
}
}
I think it has something to do with a self signed ssl certificate.
Would appreciate any help, thanks
CodePudding user response:
You can't use a self-signed certificate without first setting up the device to trust the certificate that did the signing (i.e., the certificate itself, since it signed itself). So you will need to find a way to open that certificate in iOS so that it can be added to the device's trusted certificate store. You could email it to yourself then tap on the attachment, or put it into iCloud Drive and open it from Drive on the phone. Then got to Settings and search for Trusted Certificates and go there to mark this certificate as trusted.
You might find it easier to just get a real cert for your server, such as a free one using certbot.eff.org
CodePudding user response:
Add this in your info.plist and your issue will be solved.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
PS: this issue is occurring because your server on which your api is hosted has no SSL certificate this key will bypass that.