[已解决]swift中HTTP异步的代码立刻返回失败

参考了别人的HTTP的swift版本的代码:

执行起来遇到个问题:
func loginRemoteServer(userIdStr:String) -> (Bool, JSON?) {
    print("userIdStr=\(userIdStr)")

    var loginSuccessful:Bool = false

    /*
    http://xxx:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01
    {
        "active": true,
        "contacts": [
            "contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e",
            "contact-351e6499-142b-4d89-bf79-0f756ee41a32",
            "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"
        ],
        "doc_type": "user",
        "email": "crifan@daryun.com",
        "password": "111111",
        "pinned": []
    }
    */

    var decodedJsonDict:JSON?

    let loginUrlBase:String = "http://192.168.1.110:5000/users/"
    let fullLoginUrl:String = loginUrlBase + userIdStr

    let params:Dictionary<String, AnyObject>? = nil

    print("fullLoginUrl=\(fullLoginUrl)")
    //http://xxx:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01

    do {
        let opt = try HTTP.GET(
                fullLoginUrl,
                parameters: params,
                requestSerializer: JSONParameterSerializer())

        opt.start { response in
            if let err = response.error {
                print("error: \(err.localizedDescription)")
                return
            }

            print("opt finished: \(response.description)")
            /*
            opt finished: URL:
            http://192.168.1.110:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01

            Status Code:
            200

            Headers:
            Server: Werkzeug/0.11.2 Python/3.5.0
            Content-Type: application/json
            Date: Sat, 21 Nov 2015 06:14:26 GMT
            Content-Length: 342

            Payload:
            {
            "active": true,
            "contacts": [
            "contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e",
            "contact-351e6499-142b-4d89-bf79-0f756ee41a32",
            "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"
            ],
            "doc_type": "user",
            "email": "crifan@daryun.com",
            "password": "111111",
            "pinned": []
            }
            */
            print("response.statusCode=\(response.statusCode)")

            decodedJsonDict = JSON(data: response.data)
            print("decodedJsonDict=\(decodedJsonDict)")

            if decodedJsonDict!["active"].bool! {
                loginSuccessful = true

                NSLog("Login OK, decodedJsonDict=\(decodedJsonDict)")
            }else {
                NSLog("Login Fail, decodedJsonDict=\(decodedJsonDict)")
            }
        }
    } catch let httpGetError {
        NSLog("http get url=\(fullLoginUrl) with params=\(params) got error= \(httpGetError)")
    }

    return (loginSuccessful, decodedJsonDict)
}
代码是异步的,有时候代码的response还没执行完毕,程序就立刻返回了。。。
导致登陆失败。。。
搜:
swift http response
swift http response immediately return
swift http return
参考:
参考:
swift http 异步 代理
swift http synchronous
参考:
最后用:
func loginRemoteServer(userIdStr:String) -> (Bool, JSON?) {
    print("userIdStr=\(userIdStr)")

    var loginSuccessful:Bool = false

    /*
    http://192.168.1.110:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01
    {
        "active": true,
        "contacts": [
            "contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e",
            "contact-351e6499-142b-4d89-bf79-0f756ee41a32",
            "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"
        ],
        "doc_type": "user",
        "email": "crifan@daryun.com",
        "password": "111111",
        "pinned": []
    }
    */

    var decodedJsonDict:JSON?

    let loginUrlBase:String = "http://192.168.1.110:5000/users/"
    let fullLoginUrl:String = loginUrlBase + userIdStr

    print("fullLoginUrl=\(fullLoginUrl)")
    //http://192.168.1.110:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01

    //Synchronous request
    let fullNsurl: NSURL = NSURL(string: fullLoginUrl)!
    print("fullNsurl=\(fullNsurl)") //fullNsurl=http://192.168.1.110:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01
    let userLoginReq: NSURLRequest = NSURLRequest(URL: fullNsurl)
    print("userLoginReq=\(userLoginReq)") //userLoginReq=<NSURLRequest: 0x7f9280eac650> { URL: http://192.168.1.110:5000/users/user-cfa5bf5a-2d39-4141-a092-627b9892fe01 }
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil
    do {
        let respJsonData: NSData =  try NSURLConnection.sendSynchronousRequest(userLoginReq, returningResponse: response)
        print("response=\(response)") //response=0x0000000000000000
        print("respJsonData=\(respJsonData)") //respJsonData=<7b0a2020 22616374 69766522 3a207472 75652c0a 20202263 6f6e7461 63747322 3a205b0a 20202020 22636f6e 74616374 2d303935 64656331 642d3962 66322d34 3565332d 62646338 2d346631 30616366 37636437 65222c0a 20202020 22636f6e 74616374 2d333531 65363439 392d3134 32622d34 6438392d 62663739 2d306637 35366565 34316133 32222c0a 20202020 22636f6e 74616374 2d333965 65313239 392d3465 32392d34 3363662d 39303466 2d643838 32366365 31623839 39220a20 205d2c0a 20202264 6f635f74 79706522 3a202275 73657222 2c0a2020 22656d61 696c223a 20226372 6966616e 40646172 79756e2e 636f6d22 2c0a2020 226e616d 65223a20 225c7536 3734655c 75383330 32222c0a 20202270 61737377 6f726422 3a202231 31313131 31222c0a 20202270 686f6e65 223a2022 31353035 31343634 36353422 2c0a2020 2270696e 6e656422 3a205b5d 0a7d>

        decodedJsonDict = JSON(data: respJsonData)
        print("decodedJsonDict=\(decodedJsonDict)")
        /*
            decodedJsonDict=Optional({
            "active" : true,
            "pinned" : [

            ],
            "password" : "111111",
            "contacts" : [
                "contact-095dec1d-9bf2-45e3-bdc8-4f10acf7cd7e",
                "contact-351e6499-142b-4d89-bf79-0f756ee41a32",
                "contact-39ee1299-4e29-43cf-904f-d8826ce1b899"
            ],
            "doc_type" : "user",
            "email" : "crifan@daryun.com",
            })
        */

        if decodedJsonDict!["active"].bool! {
            loginSuccessful = true

            NSLog("Login OK, decodedJsonDict=\(decodedJsonDict)")
        }else {
            NSLog("Login Fail, decodedJsonDict=\(decodedJsonDict)")
        }

    }catch let httpGetErr {
        print("httpGetErr=\(httpGetErr)")
    }

    return (loginSuccessful, decodedJsonDict)
}
实现了,同步HTTP请求。
虽然对于在主UI线程中,执行同步的HTTP请求,不是太好的做法
但是目前基本满足需求。
等后续参考:
再优化为异步的HTTP,然后或许加上对应代理delegate去处理获取到response后的动作。
[后记]
后来经过多次调用,优化,已变为:
//Synchronous request, to get url response json dict
func getUrlRespJsonDict(url:String) -> JSON? {
    print("getUrlRespJsonDict: url=\(url)")

    var decodedJsonDict:JSON?
    
    let fullNsurl: NSURL = NSURL(string: url)!
    print("fullNsurl=\(fullNsurl)")
//    let urlReq: NSURLRequest = NSURLRequest(URL: fullNsurl)

    let mutableUrlReq:NSMutableURLRequest = NSMutableURLRequest(URL: fullNsurl)

    //add header
//    mutableUrlReq.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Content-Type")
    mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Accept")
    
    print("mutableUrlReq=\(mutableUrlReq)") //mutableUrlReq=<NSMutableURLRequest: 0x7f8543c92850> { URL: http://192.168.1.234:8080/user?phone=xxxxxx }
    
    do {
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil
        let respJsonData: NSData =  try NSURLConnection.sendSynchronousRequest(mutableUrlReq, returningResponse: response)
        //print("response=\(response)") //response=0x0000000000000000

        //print("respJsonData=\(respJsonData)") //respJsonData=<5b7b225f 6964223a 22757365 722d6165 36663833 32622d30 3762382d 34636330 2d396132 352d3234 32323432 66393865 3864222c 2270696e 6e656422 3a5b5d2c 22746561 6d73223a 5b5d2c22 63726561 74655f74 696d6522 3a223230 31352d31 312d3232 5430323a 34363a33 382e3936 345a222c 22616374 69766522 3a747275 652c2272 65636569 76656422 3a5b5d2c 2275706c 6f616473 223a5b5d 2c227570 64617465 5f74696d 65223a22 32303135 2d31312d 32325430 323a3436 3a33382e 3936345a 222c2270 686f6e65 223a2231 35303531 34363436 3534222c 226e616d 65223a22 e69d8ee8 8c82222c 226c6f63 6b656422 3a66616c 73652c22 656d6169 6c223a22 63726966 616e406a 69616e64 616f2e69 6d222c22 636f6e74 61637473 223a5b5d 7d5d>
        
        decodedJsonDict = JSON(data: respJsonData)
//        print("decodedJsonDict=\(decodedJsonDict)")

        /*
        decodedJsonDict=Optional([
        {
        "email" : "crifan@jiandao.im",
        "active" : true,
        "_id" : "user-ae6f832b-07b8-4cc0-9a25-242242f98e8d",
        "pinned" : [
        
        ],
        "locked" : false,
        "received" : [
        
        ],
        "contacts" : [
        
        ],
        "teams" : [
        
        ],
        "create_time" : "2015-11-22T02:46:38.964Z",
        "uploads" : [
        
        ],
        "update_time" : "2015-11-22T02:46:38.964Z"
        }
        ])

        */
    }catch let httpGetErr {
        print("httpGetErr=\(httpGetErr)")
        
        decodedJsonDict = nil
    }
    
    return decodedJsonDict
}


发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量