【问题标题】:Function Return value at the Beginning [duplicate]函数开头的返回值[重复]
【发布时间】:2023-04-09 06:24:01
【问题描述】:

当我调用这个函数时,函数返回值,然后做所有其他事情。我怎样才能使函数返回其他事物的值结束。

    func register(parameters : [String : String]) -> Int {

    let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache",
    ]
    var statuscode = 0
    var postD = NSData();
    do {
        let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted)
        postD = postData;
    }catch let error as NSError{
        print(error.description)
    }
    var request = NSMutableURLRequest(URL: NSURL(string: "\(hostUrl)/users")!,
                                      cachePolicy: .UseProtocolCachePolicy,
                                      timeoutInterval: 10.0)

    request.HTTPMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.HTTPBody = postD

    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? NSHTTPURLResponse
            statuscode = httpResponse!.statusCode
            print("AFTER HTTP RESPONSE STATUSCODE = \(statuscode)")

        }
    })

    dataTask.resume()
    return statuscode
}

我这样调用这个函数:

let statuscode = client.register(parameters)
        print("denemeeeeeeeeeeeeee\(statuscode)")

这是我的输出

denemeeeeeeeeeeeeee0
AFTER HTTP RESPONSE STATUSCODE = 400

【问题讨论】:

    标签: ios swift swift2 swift3


    【解决方案1】:

    NSURLSession是一个异步API,所以恐怕你的函数总是在数据请求完成之前返回。您将不得不考虑替代方法。例如,您的 register 方法可能会收到您在数据任务完成时调用的完成闭包。

    【讨论】:

      【解决方案2】:

      你需要实现一个callback 函数来处理这种事情:

      func register(parameters : [String : String], callback: ((success: Bool, response: NSHTTPURLResponse)->Void){
      
      let headers = [
          "content-type": "application/json",
          "cache-control": "no-cache",
      ]
      var postD = NSData();
      do {
          let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted)
          postD = postData;
      }catch let error as NSError{
          print(error.description)
      }
      var request = NSMutableURLRequest(URL: NSURL(string: "\(hostUrl)/users")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                        timeoutInterval: 10.0)
      
      request.HTTPMethod = "POST"
      request.allHTTPHeaderFields = headers
      request.HTTPBody = postD
      
      let session = NSURLSession.sharedSession()
      let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
          if (error != nil) {
              print(error)
          } else {
      
              let httpResponse = response as? NSHTTPURLResponse
              callback?(success: true, response: httpResponse)
      
      
          }
      })
      
      dataTask.resume()
      }
      

      在你的函数调用中:

      client.register(parameters, callback: { (success, response) in
           var statuscode = 0
           statuscode = response!.statusCode
           print("AFTER HTTP RESPONSE STATUSCODE = \(statuscode)")
      })
      

      如果这还不足以实现您想要做的事情,您还可以查看dispatch groups

      祝你好运。

      【讨论】:

      • 这是更简单的解决方案,您可以删除退货,因为它不需要并且总是不正确
      • 正确,我已删除答案中未使用的退货。
      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2016-01-12
      • 2020-02-20
      相关资源
      最近更新 更多