最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[基本解决]swift优化http网络请求部分的代码

Swift crifan 2979浏览 0评论

之前的http的代码如下:

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

    do {
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil
        let respJsonData: NSData =  try NSURLConnection.sendSynchronousRequest(mutableUrlReq, returningResponse: response)

        decodedJsonDict = JSON(data: respJsonData)
        print("decodedJsonDict=\(decodedJsonDict)")

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

        decodedJsonDict = nil
    }

    return decodedJsonDict
}
现在需要优化:
根据iOS版本不同,决定是否继续用sendSynchronousRequest还是换其他函数
-》因为sendSynchronousRequest已经在iOS 9中废弃不用了
搜:
搜:
swift NSURLConnection sendSynchronousRequest replacement
参考:
搜:
swift dataTaskWithRequest
参考:
搜:
swift datataskwithrequest synchronous
参考:
-》
结论:
应该完全避免使用同步的HTTP
而改用异步的HTTP请求
想办法,优化如何使用异步的http
-》暂时还是使用Swift HTTP
-》或者使用自带的API:
NSURLSession的dataTaskWithRequest去完成异步请求
因为它支持callback
->后来自己研究代码后发现,Swift HTTP也是支持completionHandler的:
swift completionHandler http response
-》如此,就可以去封装一个函数,填入callback了。
暂时改为:
func getUrlRespJsonDict_async(url:String, extraParas:AnyObject?, respJsonDictHandler:((Bool, AnyObject?, JSON) -> Void)) {
    print("url=\(url)")

    var getJsonOk:Bool = false
    let params:Dictionary<String, AnyObject>? = nil

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

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

                getJsonOk = false
                let errJsonDict = JSON(["error" : err.localizedDescription])
                respJsonDictHandler(getJsonOk, extraParas, errJsonDict)
                return
            }

            print("response.statusCode=\(response.statusCode)")
            print("opt finished: \(response.description)")

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

            getJsonOk = true
            respJsonDictHandler(getJsonOk, extraParas, decodedJsonDict)
        }
    } catch let httpGetError {
        NSLog("http get url=\(url) with params=\(params) got error= \(httpGetError)")

        getJsonOk = false
        let errJsonDict = JSON(["error" : "\(httpGetError)"])
        respJsonDictHandler(getJsonOk, extraParas, errJsonDict)
    }
}
调用方式:
        let getContactIdListUrl:String = StrServerUrl + "/user/" + userIdStr + "/teams/joined/" + teamIdStr + "/members"
        let userTeamInfoDict:[String:String] = ["userIdStr":userIdStr, "teamIdStr":teamIdStr]
        getUrlRespJsonDict_async(getContactIdListUrl, extraParas: userTeamInfoDict, respJsonDictHandler: contactIdListJsonDictHandler)

    func contactIdListJsonDictHandler(getJsonOk:Bool, extraParas:AnyObject?, respJsonDict:JSON){
        if getJsonOk {
            var contactIdList:[String] = [String]()
            contactIdList = respJsonDict.arrayObject as! [String]
            print("contactIdList=\(contactIdList)") //

。。。
            }
        }

    }
[后记]
之后,经过无数次改进后,变为:
func getUrlRespJsonDict_async(url:String, extraParas:AnyObject?, respJsonDictHandler:((Bool, AnyObject?, JSON) -> Void)) {
    gLog.debug("url=\(url), extraParas=\(extraParas), respJsonDictHandler=\(respJsonDictHandler)")

    var extraParas = extraParas

    var getJsonOk:Bool = false
    var params:Dictionary<String, AnyObject>? = nil
    var headers:Dictionary<String, String>? = nil

    var opt:HTTP? = nil
    var httpVerb:String? = nil

    if extraParas != nil {
        if extraParas is Dictionary<String, AnyObject> {
            extraParas = extraParas as! Dictionary<String, AnyObject>

            if let httpParams = extraParas!["httpParams"] {
                gLog.debug("httpParams=\(httpParams)")
                
                if httpParams != nil {
                    params = httpParams as? Dictionary<String, AnyObject>
                    //Optional(["Authorization": Basic dXNlci04N2YzYWRkOS1iMTJlLTQ3OWMtYjE1NS02MWQ3MzMzNjZkY2Y6MTExMTEx])
                    //Optional(["text": To bl])
                    //Optional(["last": message-36dda308-be05-4769-be0d-51ed1cd511ef, "date": 20151212])
                    //Optional(["topic": false, "desc": 聊聊职业生涯规划,欢迎大家围观哦, "name": 职业生涯规划])
                }
            }

            if let httpHeaders = extraParas!["httpHeaders"] {
                gLog.debug("httpHeaders=\(httpHeaders)")
                if httpHeaders != nil {
                    headers = httpHeaders as? Dictionary<String, String>
                    /*
                    get token:
                    Optional({
                    Authorization = "Basic dXNlci04N2YzYWRkOS1iMTJlLTQ3OWMtYjE1NS02MWQ3MzMzNjZkY2Y6MTExMTEx";
                    })
                    */
                    
                    /*
                    follow url will require token header:
                    authenticate: token xxxxxx
                    */
                }
            }
            
            if let httpVerbStr = extraParas!["httpVerb"] {
                gLog.debug("httpVerbStr=\(httpVerbStr)")
                //Note: httpVerbStr is nil, but code still can go into here!!!
                httpVerb = httpVerbStr as? String
                //Optional("POST")
                //nil
                //Optional("PUT")
            }
        }
    }

    if !gCurUserItem.accessToken.isEmpty {
        if headers == nil {
            headers = Dictionary<String, String>()
            headers!["authenticate"] = "token " + gCurUserItem.accessToken
        } else {
            headers!["authenticate"] = "token " + gCurUserItem.accessToken
        }

        gLog.debug("headers=\(headers)")
        //headers=Optional(["authenticate": "token 7au5urb4cqp2oeb6uidcgbnk7m"])
    }
    
    do {
        if (httpVerb != nil) && !(httpVerb!.isEmpty) {
            switch httpVerb!{
            case String(HTTPVerb.GET):
                opt = try HTTP.GET(
                    url,
                    parameters: params,
                    headers: headers,
                    requestSerializer: JSONParameterSerializer())
            case String(HTTPVerb.POST):                
                opt = try HTTP.POST(
                    url,
                    parameters: params,
                    headers: headers,
                    requestSerializer: JSONParameterSerializer())
            case String(HTTPVerb.PUT):
                opt = try HTTP.PUT(
                    url,
                    parameters: params,
                    headers: headers,
                    requestSerializer: JSONParameterSerializer())
            case String(HTTPVerb.DELETE):
                opt = try HTTP.DELETE(
                    url,
                    parameters: params,
                    headers: headers,
                    requestSerializer: JSONParameterSerializer())

            default:
                opt = try HTTP.GET(
                    url,
                    parameters: params,
                    headers: headers,
                    requestSerializer: JSONParameterSerializer())
            }
        }else{
            opt = try HTTP.GET(
                url,
                parameters: params,
                headers: headers,
                requestSerializer: JSONParameterSerializer())
        }

        opt!.start { response in
            if let err = response.error {
                gLog.error("url=\(url) with params=\(params) response error= \(response.statusCode) \(err.localizedDescription)")

                getJsonOk = false
                
                var errorStr:String = "Unkown error"
                let respErrorJsonDict:JSON = JSON(data: response.data)
                if let errorMessage = respErrorJsonDict["message"].string {
                    errorStr = errorMessage
                } else {
                    errorStr = err.localizedDescription
                }

                //let errJsonDict = JSON(["error" : errorStr])
                var errorDict:[String:AnyObject] = ["error" : errorStr]
                if let statusCode = response.statusCode {
                    errorDict["statusCode"] = statusCode
                }
                let errJsonDict = JSON(errorDict)
                respJsonDictHandler(getJsonOk, extraParas, errJsonDict)
                return
            }

            //print("response.statusCode=\(response.statusCode)")
            //print("opt finished: \(response.description)")
            
            let respJsonDict:JSON
            
            let decodedJsonDict:JSON = JSON(data: response.data)
//            print("decodedJsonDict=\(decodedJsonDict)")
            
            /*
            {
            "data" : "user-a55eaa80-419f-46ac-aa56-a03d37e05854",
            "message" : "ok",
            "code" : 200
            }
            */
            
            //get sub field "data" json data
            //both string or dictonary all ok
            let decodedDataJsonDict:JSON = JSON(decodedJsonDict["data"].object)
            //gLog.debug("decodedDataJsonDict=\(decodedDataJsonDict)")
            
            respJsonDict = decodedDataJsonDict
            
            getJsonOk = true

            respJsonDictHandler(getJsonOk, extraParas, respJsonDict)
        }
    } catch let httpGetError {
        gLog.error("url=\(url) with params=\(params) got error= \(httpGetError)")

        getJsonOk = false
        let errJsonDict = JSON(["error" : "\(httpGetError)"])
        respJsonDictHandler(getJsonOk, extraParas, errJsonDict)
    }
}
调用方式:
        let getUserIdUrl = StrServerUrl + "/user?phone=" + userPhoneNumber
        print("getUserIdUrl=\(getUserIdUrl)") 
        getUrlRespJsonDict_async(getUserIdUrl, extraParas: nil, respJsonDictHandler: getUserIdJsonDictHandler)

    func getUserIdJsonDictHandler(getJsonOk:Bool, extraParas:AnyObject?, jsonDict:JSON) {
        if getJsonOk {
            if let respUserId = jsonDict.string {
                print("got user id [\(respUserId)] from phone [\(self.searchTextField.text!)]")
            }
        }else{
                addUserFail("不存在此注册用户!")
        }        
    }

转载请注明:在路上 » [基本解决]swift优化http网络请求部分的代码

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
86 queries in 0.194 seconds, using 22.21MB memory