swift 中的闭包正在做任何事情。我的代码执行不正常
closures in swift are doing whatever. My code execution isn't acting as is supposed
在app delegate中,在获取用户核心位置的坐标后,我想进行两次api调用。一个是我的服务器,以获取我们所在城市名称的一部分。该调用是异步的,因此我想在第二次调用 google 映射 api 之前将所有内容加载到全局变量数组中,以从 google 获取城市名称,同时使用异步调用。最后,在我加载了所有 google 数据之后,我想比较两个数组和城市名称以找到巧合。为此,我需要前两个操作结束。为此,我使用闭包,以确保在下一次操作开始之前加载所有数据。但是当我启动我的程序时,它没有发现两个数组之间有任何重合,当我设置断点时,我看到第二个数组 (google) 在 after 被加载进行了比较,这非常令人沮丧,因为我设置了很多关闭,在这个阶段我无法找到问题的根源。任何帮助,将不胜感激。
这是应用委托:
let locationManager = CLLocationManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Language detection
let pre = NSLocale.preferredLanguages()[0]
print("language= \(pre)")
//Core Location
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
//Clore Location
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
//Load cities slug via api call
let apiCall : webApi = webApi()
apiCall.loadCitySlugs(){(success) in
//Slug loaded in background
//Call google api to compare the slug
apiCall.loadGoogleContent(){(success) in //this function is called after compareGoogleAndApiSlugs()
apiCall.compareGoogleAndApiSlugs() //this one called before
}
}
}
return true
}
这是我的全局变量swift文件:
import Foundation
import CoreLocation
let weatherApiKey : String = "" //weather api key
var globWeatherTemp : String = ""
var globWeatherIcon : String = ""
var globCity : String = ""
var globCountry : String = ""
let googleMapsApiKey : String = ""
let googlePlacesApiKey : String = ""
var TableData:Array< String > = Array < String >()
var nsDict = []
var locValue : CLLocationCoordinate2D = CLLocationCoordinate2D()
typealias SuccessClosure = (data: String?) -> (Void)
typealias FinishedDownload = () -> ()
typealias complHandlerAsyncCall = (success : Bool) -> Void
typealias complHandlerCitySlug = (success:Bool) -> Void
typealias complHandlerAllShops = (success:Bool) -> Void
typealias googleCompareSlugs = (success:Bool) -> Void
var flagCitySlug : Bool?
var flagAsyncCall : Bool?
var flagAllShops : Bool?
var values : [JsonArrayValues] = []
var citySlug : [SlugArrayValues] = []
var asyncJson : NSMutableArray = []
let googleJson : GoogleApiJson = GoogleApiJson()
这是应用程序委托中调用的第一个函数,它调用我的服务器来加载 city slug:
func loadCitySlugs(completed: complHandlerCitySlug){
//Configure Url
self.setApiUrlToGetAllSlugs()
//Do Async call
asyncCall(userApiCallUrl){(success)in
//Reset Url Async call and Params
self.resetUrlApi()
//parse json
self.parseSlugJson(asyncJson)
flagCitySlug = true
completed(success: flagCitySlug!)
}
}
这是第二个函数,它加载 google 内容,但它是在 compareGoogleAndApiSlugs() 之后调用的,应该在...
之前调用
/*
Parse a returned Json value from an Async call with google maps api Url
*/
func loadGoogleContent(completed : complHandlerAsyncCall){
//Url api
setGoogleApiUrl()
//Load google content
googleAsyncCall(userApiCallUrl){(success) in
//Reset API URL
self.resetUrlApi()
}
flagAsyncCall = true // true if download succeed,false otherwise
completed(success: flagAsyncCall!)
}
最后是异步调用,有两个但它们几乎是相同的代码:
/**
Simple async call.
*/
func asyncCall(url : String, completed : complHandlerAsyncCall)/* -> AnyObject*/{
//Set async call params
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postParam.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
asyncJson = responseString!.parseJSONString! as! NSMutableArray
flagAsyncCall = true // true if download succeed,false otherwise
completed(success: flagAsyncCall!)
}
task.resume()
}
如果有人能看到这个问题或提出一些建议,我们将不胜感激。
这个函数有问题:
func loadGoogleContent(completed : complHandlerAsyncCall){
setGoogleApiUrl()
googleAsyncCall(userApiCallUrl){(success) in
self.resetUrlApi()
}
flagAsyncCall = true
completed(success: flagAsyncCall!) //THIS LINE IS CALLED OUTSIDE THE googleAsyncCall..
}
上述完成块是在 googleAsyncCall 块之外调用的。
代码应该是:
func loadGoogleContent(completed : complHandlerAsyncCall){
setGoogleApiUrl()
googleAsyncCall(userApiCallUrl){(success) in
self.resetUrlApi()
flagAsyncCall = true
completed(success: flagAsyncCall!)
}
}
顺便说一句..你的全局变量不是原子的..所以要小心。
在app delegate中,在获取用户核心位置的坐标后,我想进行两次api调用。一个是我的服务器,以获取我们所在城市名称的一部分。该调用是异步的,因此我想在第二次调用 google 映射 api 之前将所有内容加载到全局变量数组中,以从 google 获取城市名称,同时使用异步调用。最后,在我加载了所有 google 数据之后,我想比较两个数组和城市名称以找到巧合。为此,我需要前两个操作结束。为此,我使用闭包,以确保在下一次操作开始之前加载所有数据。但是当我启动我的程序时,它没有发现两个数组之间有任何重合,当我设置断点时,我看到第二个数组 (google) 在 after 被加载进行了比较,这非常令人沮丧,因为我设置了很多关闭,在这个阶段我无法找到问题的根源。任何帮助,将不胜感激。
这是应用委托:
let locationManager = CLLocationManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Language detection
let pre = NSLocale.preferredLanguages()[0]
print("language= \(pre)")
//Core Location
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
//Clore Location
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
//Load cities slug via api call
let apiCall : webApi = webApi()
apiCall.loadCitySlugs(){(success) in
//Slug loaded in background
//Call google api to compare the slug
apiCall.loadGoogleContent(){(success) in //this function is called after compareGoogleAndApiSlugs()
apiCall.compareGoogleAndApiSlugs() //this one called before
}
}
}
return true
}
这是我的全局变量swift文件:
import Foundation
import CoreLocation
let weatherApiKey : String = "" //weather api key
var globWeatherTemp : String = ""
var globWeatherIcon : String = ""
var globCity : String = ""
var globCountry : String = ""
let googleMapsApiKey : String = ""
let googlePlacesApiKey : String = ""
var TableData:Array< String > = Array < String >()
var nsDict = []
var locValue : CLLocationCoordinate2D = CLLocationCoordinate2D()
typealias SuccessClosure = (data: String?) -> (Void)
typealias FinishedDownload = () -> ()
typealias complHandlerAsyncCall = (success : Bool) -> Void
typealias complHandlerCitySlug = (success:Bool) -> Void
typealias complHandlerAllShops = (success:Bool) -> Void
typealias googleCompareSlugs = (success:Bool) -> Void
var flagCitySlug : Bool?
var flagAsyncCall : Bool?
var flagAllShops : Bool?
var values : [JsonArrayValues] = []
var citySlug : [SlugArrayValues] = []
var asyncJson : NSMutableArray = []
let googleJson : GoogleApiJson = GoogleApiJson()
这是应用程序委托中调用的第一个函数,它调用我的服务器来加载 city slug:
func loadCitySlugs(completed: complHandlerCitySlug){
//Configure Url
self.setApiUrlToGetAllSlugs()
//Do Async call
asyncCall(userApiCallUrl){(success)in
//Reset Url Async call and Params
self.resetUrlApi()
//parse json
self.parseSlugJson(asyncJson)
flagCitySlug = true
completed(success: flagCitySlug!)
}
}
这是第二个函数,它加载 google 内容,但它是在 compareGoogleAndApiSlugs() 之后调用的,应该在...
之前调用 /*
Parse a returned Json value from an Async call with google maps api Url
*/
func loadGoogleContent(completed : complHandlerAsyncCall){
//Url api
setGoogleApiUrl()
//Load google content
googleAsyncCall(userApiCallUrl){(success) in
//Reset API URL
self.resetUrlApi()
}
flagAsyncCall = true // true if download succeed,false otherwise
completed(success: flagAsyncCall!)
}
最后是异步调用,有两个但它们几乎是相同的代码:
/**
Simple async call.
*/
func asyncCall(url : String, completed : complHandlerAsyncCall)/* -> AnyObject*/{
//Set async call params
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postParam.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
asyncJson = responseString!.parseJSONString! as! NSMutableArray
flagAsyncCall = true // true if download succeed,false otherwise
completed(success: flagAsyncCall!)
}
task.resume()
}
如果有人能看到这个问题或提出一些建议,我们将不胜感激。
这个函数有问题:
func loadGoogleContent(completed : complHandlerAsyncCall){
setGoogleApiUrl()
googleAsyncCall(userApiCallUrl){(success) in
self.resetUrlApi()
}
flagAsyncCall = true
completed(success: flagAsyncCall!) //THIS LINE IS CALLED OUTSIDE THE googleAsyncCall..
}
上述完成块是在 googleAsyncCall 块之外调用的。
代码应该是:
func loadGoogleContent(completed : complHandlerAsyncCall){
setGoogleApiUrl()
googleAsyncCall(userApiCallUrl){(success) in
self.resetUrlApi()
flagAsyncCall = true
completed(success: flagAsyncCall!)
}
}
顺便说一句..你的全局变量不是原子的..所以要小心。