Swift Async Alamofire返回

时间:2015-05-22 08:45:27

标签: swift asynchronous alamofire

我在返回注释上得到一个空值,我确信这是因为异步范围,我已经尝试了所有内容

 var annotations: [TestAnnotation] = []

返回值,但我不能。循环正确地将值附加到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

}

2 个答案:

答案 0 :(得分:1)

您只是在代码中返回一个空数组,丢弃结果并忽略收到的错误。如果要从异步调用返回结果,则必须异步执行。像这样:

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)

    }
}

编辑:有很多方法可以调用此方法,请查看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()
    }
}

答案 1 :(得分:-1)

试试这个:

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