在我的应用用户点按标记,我需要调用网络服务才能获取信息。我使用NSURLSession.dataTaskWithRequest然后在主队列上调用dispatch_async以向用户显示标记。但是我在dispatch_async
中尝试传递参数时遇到错误代码如下
func mapView(mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!) -> UIView! {
let request = NSMutableURLRequest(URL: NSURL(string: "http://78.27.190.58:3300/api/get_location_ratings")!)
request.HTTPMethod = "POST"
let postString = "org_id=\(marker.userData["orgId"] as! Int)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
var json = JSON(data: data!)
var rating = json["results"]["avg_stars"].doubleValue
dispatch_async(dispatch_get_main_queue()) { (mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!) -> UIView! in
self.window = NSBundle.mainBundle().loadNibNamed("infoWindow", owner: self, options: nil).first! as! infoWindow
self.window?.name.text = marker.title
self.window?.adress.text = marker.snippet
self.window?.stars.image = UIImage(named: "\(showStars((marker.userData["Rating"] as! NSString).doubleValue))")
self.window?.rating.text = String((marker.userData["Rating"] as! NSString).doubleValue)
return window
}
}
task.resume()
}
错误是
我做错了什么?
答案 0 :(得分:0)
在您的dispatch_async
中,您使用了包含两个参数(mapView
和marker
)的闭包,但没有将任何内容传递给这些参数。
答案 1 :(得分:0)
因为您使用dataTaskWithRequest
,所以您无法直接返回值。所以你必须在这种情况下使用闭包。您可以将代码更改为:
func mapView(mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!, completion:(UIView!) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://78.27.190.58:3300/api/get_location_ratings")!)
request.HTTPMethod = "POST"
let postString = "org_id=\(marker.userData["orgId"] as! Int)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
var json = JSON(data: data!)
var rating = json["results"]["avg_stars"].doubleValue
dispatch_async(dispatch_get_main_queue()) {
let view = UIView(frame: self.view.frame)
self.window = NSBundle.mainBundle().loadNibNamed("infoWindow", owner: self, options: nil).first! as! infoWindow
self.window?.name.text = marker.title
self.window?.adress.text = marker.snippet
self.window?.stars.image = UIImage(named: "\(showStars((marker.userData["Rating"] as! NSString).doubleValue))")
self.window?.rating.text = String((marker.userData["Rating"] as! NSString).doubleValue)
completion(window)
}
}
task.resume()
}
并使用它:
your_instace.mapView(mapview, markerInfoWindow: GMSMakre) { (view: UIView!) -> Void in
//do somethinghere
}