Establish synchronous connection with the sever in

2019-09-09 12:11发布

问题:

I have the following function to establish the connection synchronously with the sever on a particular IP and port, send a JSON request to sever and return the server's response to the calling function.

func connserv(jsonString:NSDictionary){

    var abc: NSDictionary?

    // This is the action performed when clicked on the Connect button on the connectivity screen

    println("------------------Function connserv")

    let prefs = NSUserDefaults.standardUserDefaults()

    var IP: AnyObject = prefs.objectForKey("IP")!

    var port: AnyObject = prefs.objectForKey("Port")!

    println("IP in Connection : \(IP)")

    println("port in Connection : \(port)")

    prefs.synchronize()


    let localizedModel = UIDevice.currentDevice().localizedModel

    let model = UIDevice.currentDevice().model

    let devicesystemVersion = UIDevice.currentDevice().systemVersion

    println("HTTP request jsonString : \(jsonString)")
    var request = NSMutableURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)
    var response: NSURLResponse?

    //var request: NSURLRequest = NSURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)
    //var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil


    var error: NSError?

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &err)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    // send the request
    println("HTTP request : \(request)")
    var e: NSError?

    NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &e)

    debugPrintln(response)

    println("response-------------------------> : \(response)")
} 

When the above function executed, server does not receive any thing and gives the following error:

HTTP request : <NSMutableURLRequest: 0x7c8bb240> { URL: https://144.1.1.45:9299/ }
2015-04-07 11:16:59.661 MyApp[996:24843] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)nil
response-------------------------> : nil
2015-04-07 11:16:59.663 MyApp[996:24600] Unknown class UIAlert in Interface Builder file.

I want to return server response (variable response) to the calling function of the connserv function. Please help me to achieve this requirement.