ios - swift 中的闭包正在做任何事情。我的代码执行不正常

标签 ios swift asynchronous swift2 nsjsonserialization

在 app delegate 中,在获取具有核心位置的用户坐标后,我想进行两次 api 调用。一个是我的服务器,以获取我们所在城市名称的一部分。该调用是异步的,因此我想在第二次调用 google map api 之前将所有内容加载到全局变量数组中,以从 google 获取城市名称,也可以使用异步调用。最后在我加载了所有谷歌数据之后,我想比较两个数组,用城市名称来找到巧合。为此,我需要前两个操作结束。为此,我使用闭包,以确保在下一次操作开始之前加载所有数据。但是当我启动我的程序时,它没有发现两个数组之间有任何重合,当我设置断点时,我看到第二个数组(google)在进行比较之后加载,这非常令人沮丧,因为我设置了很多关闭,在这个阶段我无法找到问题的根源。任何帮助,将不胜感激。

这是应用程序委托(delegate):

    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()

这是在应用委托(delegate)中调用的第一个函数,它调用我的服务器来加载 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!)
    }
}

这是第二个函数,它加载谷歌内容,但它是在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..
}

上面的完成 block 是在 googleAsyncCall block 之外调用的。

代码应该是:

func loadGoogleContent(completed : complHandlerAsyncCall){

    setGoogleApiUrl()
    googleAsyncCall(userApiCallUrl){(success) in

        self.resetUrlApi()
        flagAsyncCall = true
        completed(success: flagAsyncCall!)

    }
}

顺便说一句..你的全局变量不是原子的..所以要小心。

关于ios - swift 中的闭包正在做任何事情。我的代码执行不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37779751/

相关文章:

iphone - 自定义 CorePlot gridLineStyle

ios - 原型(prototype)单元格未显示在 UITableView 中

ios - 快速替换 'Class'

iphone - ARC 循环保留检测

ios - 无法识别的选择器发送到 ios 教程上的实例

Swift float 乘法错误

ios - 如何在iOS中找到 "NFC Tag Identifier"

javascript - javascript for 循环内的异步过程

Python cmd 模块 - 异步事件后恢复提示

javascript - canvas.toDataURL 使用数组和循环返回空数据 :, 字符串