Swift 异步 Alamofire return

Swift Async Alamofire return

我在 return 注释上得到一个空值,我确信这是因为异步范围,我已经尝试了一切来获得

 var annotations: [TestAnnotation] = []

到 return 的值,但我不能。循环正确地附加了 makeRequest 范围内的值。

func makeRequest(url : String, params : [String : String]?, completionHandler: (responseObject: JSON?, error: NSError?) -> ())  -> Request? {

    return Alamofire.request(.GET, url, parameters: params, encoding: .URL)
        .responseString { request, response, responseBody, error in completionHandler(
            responseObject:
            {
                // JSON to return
                var json : JSON?
                if let response = responseBody {
                    // Parse the response to NSData
                    if let data = (response as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
                        json = JSON(data: data)
                    }
                }

                return json

                }(), error: error)
    }
}

func annotations() -> [TestAnnotation] {
    var annotations: [TestAnnotation] = []

    var points: NSDictionary = [:]
    self.makeRequest("http://192.168.0.10/test/globe.php", params: nil) { json, error in

        if let data = json!.rawData() {
            let json = JSON(data: data)

            for var i = 0; i < json["venues"].count; i++
            {
                let lat = (json["venues"][i]["latitude"]).doubleValue as CLLocationDegrees
                let lon = (json["venues"][i]["longitude"]).doubleValue as CLLocationDegrees
                let venuesid = (json["venues"][i]["id"]).stringValue as String
                ///
                let coordinate1 : CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lon)

                let a1: TestAnnotation = TestAnnotation(coordinate: coordinate1, title: glimpid)
                annotations.append(a1)

            }
        }

    }
    return annotations

}

您只是 return 在您的代码中输入一个空数组,丢弃结果并忽略收到的错误。如果你想 return 异步调用的结果,你也必须异步执行。像这样:

func annotations(onComplete: (NSError?, [TestAnnotations]?) -> Void) {
    self.makeRequest("http://192.168.0.10/test/globe.php", params: nil) { json, error in

        var annotations: [TestAnnotations]?
        if let data = json!.rawData() {
            let json = JSON(data: data)
            annotations = [TestAnnotation]()

            for var i = 0; i < json["venues"].count; i++
            {
                let lat = (json["venues"][i]["latitude"]).doubleValue as CLLocationDegrees
                let lon = (json["venues"][i]["longitude"]).doubleValue as CLLocationDegrees
                let venuesid = (json["venues"][i]["id"]).stringValue as String
                ///
                let coordinate1 : CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lon)

                let a1: TestAnnotation = TestAnnotation(coordinate: coordinate1, title: glimpid)
                annotations?.append(a1)

            }
        }

        onComplete(error, annotations)

    }
}

EDIT: 调用这个方法有很多方法,查看Closures documentation 看看如何传递你的闭包参数。这是其中之一:

self.annotations { error, annotations in 
    // Check for errors
    if let error = error {
        NSLog("Received error: %@", error)
    }
    if let annotations = annotations {
        // Do whatever you want with your received annotations, like saving as property and reloading a table view
        self.savedAnnotations = annotations
        self.tableView.reloadData()
    }
}

试试这个:

Alamofire.request(.GET, url, parameters: params, encoding: .URL)
        .responseString { request, response, responseBody, error in completionHandler(
            responseObject:
            {
                // JSON to return
                var json : JSON?
                if let response = responseBody {
                    // Parse the response to NSData
                    if let data = (response as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
                        json = JSON(data: data)
                        self.annotations(json)
                    }
                }

                return json

                }(), error: error)
    }

func annotations(json : JSON) -> [TestAnnotation] {
    var annotations: [TestAnnotation] = []

    var points: NSDictionary = [:]

            for var i = 0; i < json["venues"].count; i++
            {
                let lat = (json["venues"][i]["latitude"]).doubleValue as CLLocationDegrees
                let lon = (json["venues"][i]["longitude"]).doubleValue as CLLocationDegrees
                let venuesid = (json["venues"][i]["id"]).stringValue as String
                ///
                let coordinate1 : CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lon)

                let a1: TestAnnotation = TestAnnotation(coordinate: coordinate1, title: glimpid)
                annotations.append(a1)

            }

    }
    return annotations
}

不知道对你有没有帮助

注意:您正在使用 Alamofire 来处理请求并使用 SwiftJSON 来轻松工作,您可以通过这样做来耦合:

Alamofire.request(.GET, url, parameters: parameters)
  .responseJSON { (req, res, json, error) in
    if(error != nil) {
      NSLog("Error: \(error)")
      println(req)
      println(res)
    }
    else {
      NSLog("Success: \(url)")
      var json = JSON(json!)
    }
  }

SwiftyJSON - Alamofire