NSURLSession dataTaskWithRequest仅适用于第一次

时间:2016-09-14 10:34:44

标签: ios swift nsurlsession nsurlsessiondatatask

我正在开发一个像往常一样的WS Call,但我不知道为什么这只会在我第一次调用它时才有效,数据第一次有值,但如果我再次调用它返回nil。如果我查看响应,我可以看到当数据为零时它返回412值。

// Request
    var endPoint = Constants.CONFIG.WS_LANZADERA

    if Utils.getEnviroment() == Constants.Environment.Develop.rawValue {
        endPoint = endPoint + Constants.WS.SHIP
    }

    let request = NSMutableURLRequest(URL: NSURL(string: endPoint)!,
                                      cachePolicy: .UseProtocolCachePolicy,
                                      timeoutInterval: Constants.REQUEST.TIMEOUT)

    request.HTTPMethod = Constants.HTTP.METHOD.POST
    request.HTTPBody = shipParams.getDictionary().dataFromHttpParameters()

    let session = NSURLSession.sharedSession()

    // Handler

    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

        if error == nil {
            let jsonResult = JSON(data: data!)
            if jsonResult["error"] != "" {
                //.arrayObject
                let proxaXMLData = jsonResult["ProsaXMLData"]
                let SPM = proxaXMLData[3]
                //let userList :Array<User> = Mapper<User>().mapArray(dict)!
                //let user = userList[0]
                self.webServiceDelegates.forEach({ (delegate) -> () in
                    if (delegate.respondsToSelector(#selector(WebServiceDelegate.responseShipListSuccess))) {
                        delegate.responseShipListSuccess?()
                    }
                })
            } else {
                self.webServiceDelegates.forEach({ (delegate) -> () in
                    if (delegate.respondsToSelector(#selector(WebServiceDelegate.responseShipListFailed(_:message:)))) {
                        delegate.responseShipListFailed!(jsonResult["error"]["code"].string!, message: jsonResult["error"]["message"].string!)
                    }
                })
            }

        }
        else {
            self.webServiceDelegates.forEach({ (delegate) -> () in
                if (delegate.respondsToSelector(#selector(WebServiceDelegate.responseShipListFailed(_:message:)))) {
                    delegate.responseShipListFailed!(error!.code.description, message: error!.localizedDescription)
                }
            })
        }
    })

    dataTask.resume()

任何人都知道吗?

1 个答案:

答案 0 :(得分:1)

通过更改cachePolicy

解决
let request = NSMutableURLRequest(URL: NSURL(string: endPoint)!,
                                          cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
                                          timeoutInterval: Constants.REQUEST.TIMEOUT)