11.3 C
New York
Thursday, November 21, 2024

swift – Improvement iOS App unable to hook up with a self-signed SSL cert Safe WebSocket Server HTTP(s) – Stack Overflow


As a consequence of my iPhone being upgraded to iOS 16.6, it appears to not help a HTTP WebSocket Server connection. Simply wish to additionally say I’ve no prior expertise with iOS app growth so any assist and steerage is appreciated.

Downside to resolve: I’ve been trying to vary the codes the place I create a HTTP(s) server and advertise to the WebSocket Server to finally get the iOS app to attach with the brand new HTTP(s) WebSocket Server.

Background: The software program engineer who coded the iOS app mentioned it was written to hook up with a SimpleWebsocket Server (HTTP) utilizing iOS’s built-in Websocket help by way of ‘URLSessionWebsocketTask’ and ever for the reason that iOS model improve on the iPhone, it’s unable to hook up with the HTTP server.

The codes for the iOS app are in .swift and utilizing XCode to compile and obtain the app into the iPhone. The creation of the WebSocket Server is in .py together with the GUI controller for the app.

Initially to get all the things operating, I’d set-up the WebSocket Server utilizing Ubuntu from the Python script since I’m controlling the iOS app by way of one other Python script driver which gives a GUI to regulate the app on a Home windows laptop (the pc additionally gives a cellular hotspot that’s linked to within the iPhone to have the ability to hook up with the server).

The adjustments so as from my try to convert HTTP server to HTTP(S):

  1. Created a self-signed SSL certificates with the cellular hotspot IP handle because the Widespread Identify.

  2. Downloaded and trusted the self-signed SSL certificates on the iPhone

  3. Modified the WebSocketClient.py that’s ran in Ubuntu to simply accept and use SSL cert (operating this exhibits the Safe WebSocket Server is began on the port inputted)

  4. Up to date the Python Driver.py script (GUI to regulate iOS app) on the Home windows laptop to hook up with the Safe WebSocket Server (this additionally exhibits it’s linked to the Safe WebSocket Server)

  5. Every little thing appears to be like good at this level

  6. Now, after I hook up with the cellular hotspot from the Home windows laptop, I transfer onto the iPhone iOS app the place it wants to hook up with the server as effectively so within the iOS app swift code for the server connection, I modified the unique ws:// to wss:// and re-downloaded the app to the iPhone however it’s unable to hook up with the server (within the Ubuntu terminal, it will present if it connects however nothing occurs now).

  7. Debugging the connection to the WebSocket Server, this error happens: Error Area=NSURLErrorDomain Code=-1009 “The Web connection seems to be offline.”

    1. I do know for sure the cellular hotspot has web connection since I used DropBox to obtain the cert.pem for the SSL certification to belief it

Primarily based on these makes an attempt I attempted, what’s lacking in my steps to get the iOS app/iPhone linked to the HTTP(S) server? Would I would like so as to add adjustments to the iOS app’s information.plist (Info Property Listing) to work with HTTP(s) together with the iOS app’s WebSocketConnection.swift? Thanks upfront.

Codes for the iOS app that I imagine are related to the WebSocketServer:
Information.plist the place I added the traces (uncertain if appropriate):

NSAppTransportSecurity:




    CFBundleDevelopmentRegion
    $(DEVELOPMENT_LANGUAGE)
    CFBundleExecutable
    $(EXECUTABLE_NAME)
    CFBundleIdentifier
    $(PRODUCT_BUNDLE_IDENTIFIER)
    CFBundleInfoDictionaryVersion
    6.0
    CFBundleName
    $(PRODUCT_NAME)
    CFBundlePackageType
    $(PRODUCT_BUNDLE_PACKAGE_TYPE)
    CFBundleShortVersionString
    1.0
    CFBundleVersion
    1
    LSRequiresIPhoneOS
    
    NSCameraUsageDescription
    ARKit reside digicam
    NSLocationWhenInUseUsageDescription
    for picture anchor
    NSAppTransportSecurity
    
        NSAllowsArbitraryLoads
        
        NSAllowsLocalNetworking
        
        NSExceptionDomains
        
            192.168.137.1
            
                NSExceptionAllowsInsecureHTTPLoads
                
                NSExceptionMinimumTLSVersion
                TLSv1.2
                NSExceptionRequiresForwardSecrecy
                
                NSIncludesSubdomains
                
            
        
    
    UIApplicationSceneManifest
    
        UIApplicationSupportsMultipleScenes
        
        UISceneConfigurations
        
            UIWindowSceneSessionRoleApplication
            
                
                    UISceneConfigurationName
                    Default Configuration
                    UISceneDelegateClassName
                    $(PRODUCT_MODULE_NAME).SceneDelegate
                    UISceneStoryboardFile
                    Major
                
            
        
    
    UIApplicationSupportsIndirectInputEvents
    
    UILaunchStoryboardName
    LaunchScreen
    UIMainStoryboardFile
    Major
    UIRequiredDeviceCapabilities
    
        armv7
    
    UISupportedInterfaceOrientations
    
        UIInterfaceOrientationPortrait
        UIInterfaceOrientationLandscapeLeft
        UIInterfaceOrientationLandscapeRight
    
    UISupportedInterfaceOrientations~ipad
    
        UIInterfaceOrientationPortrait
        UIInterfaceOrientationPortraitUpsideDown
        UIInterfaceOrientationLandscapeLeft
        UIInterfaceOrientationLandscapeRight
    


//
//  WebSocketConnection.swift
//  WebSockets
//
//  Created by zen on 6/17/19.
//  Copyright © 2019 AppSpector. All rights reserved.
//

import Basis
import Mix

protocol WebSocketConnection {
    func ship(textual content: String)
    func ship(information: Knowledge)
    func join()
    func disconnect()
    var delegate: WebSocketConnectionDelegate? {
        get
        set
    }
}

protocol WebSocketConnectionDelegate {
    func onConnected(connection: WebSocketConnection)
    func onDisconnected(connection: WebSocketConnection, error: Error?)
    func onError(connection: WebSocketConnection, error: Error)
    func onMessage(connection: WebSocketConnection, textual content: String)
    func onMessage(connection: WebSocketConnection, information: Knowledge)
}

class WebSocketTaskConnection: NSObject, WebSocketConnection, URLSessionWebSocketDelegate {
    var delegate: WebSocketConnectionDelegate?
    var webSocketTask: URLSessionWebSocketTask!
    var urlSession: URLSession!
    let delegateQueue = OperationQueue()
    
    // Commented out under - ML 11/18/2024
    // init(url: URL) {
    //     tremendous.init()
    //     urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: delegateQueue)
    //     webSocketTask = urlSession.webSocketTask(with: url)
    // }

    // Up to date init() for configuration with SSL - ML 11/18/2024
    init(url: URL) {
        tremendous.init()
        
        // Create URLSession configuration with SSL settings
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForResource = 30 // Regulate timeout if wanted
        
        urlSession = URLSession(configuration: config, 
                              delegate: self, 
                              delegateQueue: delegateQueue)
        
        // Create WebSocket activity with the URL
        var request = URLRequest(url: url)
        request.setValue("", forHTTPHeaderField: "Origin") // Deal with any CORS points
        webSocketTask = urlSession.webSocketTask(with: request)
    }
    
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
        self.delegate?.onConnected(connection: self)
    }
    
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, cause: Knowledge?) {
        self.delegate?.onDisconnected(connection: self, error: nil)
    }

    // Added extra func urlSession() to simply accept/belief SSL - ML 11/18/2024
    func urlSession(_ session: URLSession, didReceive problem: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        guard problem.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
              let serverTrust = problem.protectionSpace.serverTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        
        let credential = URLCredential(belief: serverTrust)
        completionHandler(.useCredential, credential)
    }
    
    func join() {
        webSocketTask.resume()
        
        pay attention()
    }
    
    func disconnect() {
        webSocketTask.cancel(with: .goingAway, cause: nil)
    }
    
    func pay attention()  {
        webSocketTask.obtain { end in
            change consequence {
            case .failure(let error):
                self.delegate?.onError(connection: self, error: error)
            case .success(let message):
                change message {
                case .string(let textual content):
                    self.delegate?.onMessage(connection: self, textual content: textual content)
                case .information(let information):
                    self.delegate?.onMessage(connection: self, information: information)
                @unknown default:
                    fatalError()
                }
                
                self.pay attention()
            }
        }
    }
    
    func ship(textual content: String) {
        webSocketTask.ship(URLSessionWebSocketTask.Message.string(textual content)) { error in
            if let error = error {
                self.delegate?.onError(connection: self, error: error)
            }
        }
    }
    
    func ship(information: Knowledge) {
        webSocketTask.ship(URLSessionWebSocketTask.Message.information(information)) { error in
            if let error = error {
                self.delegate?.onError(connection: self, error: error)
            }
        }
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles