如何进行同步GET请求

时间:2016-05-18 17:27:13

标签: ios swift rest

我的代码中有一个GET请求方法:

  func makeHTTPGetRequest(path: String, parameters: [String: AnyObject], completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionTask {

    let parameterString = parameters.stringFromHttpParameters()
    let requestURL = NSURL(string:"\(path)?\(parameterString)")!

    let request = NSMutableURLRequest(URL: requestURL)
    request.HTTPMethod = "GET"
    request.setValue("Bearer " + userInfoDefaults.stringForKey("accessToken")!, forHTTPHeaderField: "Authorization")

    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request, completionHandler:completionHandler)
    task.resume()

    return task
  }

由另一个填充特定场景中的选择器视图的方法调用:

  func getAffiliateds() -> [String]? {
    var affiliateds:[String] = []
    makeHTTPGetRequest(baseURL + "affiliateds", parameters: [:], completionHandler: { (data, response, error) in
      do {
        affiliateds = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [String]
        print (affiliateds)
      }
      catch { print("Error: \(error)") }
    })
    return affiliateds
  }

我需要从我的webservice获取所有附属机构,然后在选择器视图中列出它。但是当我调试代码时,我注意到附属项首先作为空数组返回,然后返回正确的信息。我只有在已经从webservice接收到数据时才需要从getAffiliateds返回数组。我该怎么做?

2 个答案:

答案 0 :(得分:1)

你做不到。您的getAffiliateds() 无法返回一个值,该值取决于它将运行的异步代码。这是异步代码的本质。相反,在调用它时,在完成处理程序中执行某种的回调:

makeHTTPGetRequest(baseURL + "affiliateds", parameters: [:], completionHandler: { (data, response, error) in
  do {
    affiliateds = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [String]
    print (affiliateds)
    // DO SOMETHING HERE
  }
}

一个常见的策略是让调用者提供另一个完成处理程序,这个完成处理程序将调用它。

答案 1 :(得分:1)

你有一个例程:

func getAffiliateds() -> [String]? {
    var affiliateds:[String] = []
    makeHTTPGetRequest(baseURL + "affiliateds", parameters: [:], completionHandler: { (data, response, error) in
        do {
            affiliateds = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [String]
            print (affiliateds)
        }
        catch { print("Error: \(error)") }
    })
    return affiliateds
}

你可能有一些代码可以做类似的事情:

func populatePicklist() {
    let affiliateds = getAffiliateds()
    // populate picklist here
}

您应该将其更改为:

func getAffiliatedsWithCompletionHandler(completionHandler: ([String]?) -> ()) {
    makeHTTPGetRequest(baseURL + "affiliateds", parameters: [:]) { data, response, error in
        do {
            let affiliateds = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String]  // two notes here: first, define local var here, not up above; second, use `as?` to gracefully handle problems where result was not `[String]`
            print (affiliateds)
            completionHandler(affiliateds)
        }
        catch {
            print("Error: \(error)")
            completionHandler(nil)
        }
    }
}

func populatePicklist() {
    getAffiliatedsWithCompletionHandler { affiliateds in
        // populate picklist here
    }

    // but not here
}