在swift中与服务器建立同步连接

时间:2015-04-07 06:09:36

标签: iphone swift ios8 nsurlconnection server

我有以下功能与特定IP和端口上的服务器同步建立连接,向服务器发送JSON请求并返回服务器对调用函数的响应。

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)")
} 

执行上述功能时,服务器不会收到任何内容并发出以下错误:

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.

我想将服务器响应(变量响应)返回给connserv函数的调用函数。请帮我实现这个要求。

0 个答案:

没有答案