在swift中显示启动画面时进行API调用

时间:2014-09-04 06:59:55

标签: ios swift

我知道如何在Swift中制作启动画面。但是我想在显示启动画面时调用一个函数,它将进行API调用。我试着这样做:

func showSpinner(actInd: UIActivityIndicatorView){
    actInd.center = self.view.center
    actInd.hidesWhenStopped = true
    actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    self.view.addSubview(actInd)
    actInd.startAnimating()
}

func stopSpinner(actInd: UIActivityIndicatorView){
    actInd.stopAnimating()
}

func getStrings(){
    var apiParams = NSDictionary() as Dictionary<String, AnyObject>
    apiParams["p1"] = "2"
    apiParams["p2"] = "3"
    callBaseApi("getstrings", "http://swt.com/xyz/", apiParams)
}

func callBaseApi(path: String, basePath: String, params: NSDictionary){
    println("123")           //<- This is not getting printed
    var jsonSerializationError = NSError?()
    var jsonData = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &jsonSerializationError)
    var url = basePath + path
    var request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = jsonData
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error = NSError?()
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
        if (jsonResult != nil) {
            // process jsonResult
            println("Result came")
        } else {
            // couldn't load JSON, look at error
        }
    })
}

override func viewDidLoad(){
    ...
    var actInd = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
    self.showSpinner(actInd)
    self.getStrings()
    self.stopSpinner(actInd)
}

正如您所看到的,getStrings正在调用callBaseApi,它不会打印任何内容。如果我调用self.getStrings函数并在模拟器中运行代码,我会看到一个黑屏。但是,如果我在self.getStrings内调用dispatch_async函数,就像这样

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    self.getStrings()
})

我看到了启动画面,但是getStrings函数似乎没有进行任何API调用。我哪里错了?请帮忙。

0 个答案:

没有答案