ios swift程序流程

时间:2015-09-17 15:00:33

标签: ios json swift flow

在我的mainviewcontroller的viewDidLoad()方法中,我正在触发几个进程。

        let api = JsonData() // create instance of JsonData class
        api.loadJson(nil) // this method receives json and writes it in the file.

    //Function to find file location
    func getFileURL(fileName: String) -> NSURL {
        let manager = NSFileManager.defaultManager()
        let dirURL = manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false, error: nil)
        return dirURL!.URLByAppendingPathComponent(fileName)
    }
         //file with this name was created in loadJson method
        let filePath = getFileURL("JSONFromServer.txt").path!

   //trying to read this file
 let newDictionary = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! [Dictionary <String,AnyObject> ]

我希望该文件将在api.loadJson中创建,然后我就可以直接阅读它了。但由于某些原因,当我使用调试器时,我发现还没有文件。只有当程序从viewdidload方法中退出时,我才能看到该文件已创建。

我想知道程序流程是否具体?

这是我的JsonData类:

import Foundation

class JsonData {

    var bankDict  = [Dictionary <String,AnyObject> ]()
    var arrayOfBanks: [[String:AnyObject]] = []

    func loadJson(completion: ((AnyObject) -> Void)!) {

        var urlString = "http://almaz.com/getjson.php"

        let session = NSURLSession.sharedSession()
        let sourceUrl = NSURL(string: urlString)

        var task = session.dataTaskWithURL(sourceUrl!){

            (data, response, error) -> Void in

                if error != nil {
                    println(error.localizedDescription)
                } else {

                    var error: NSError?

                    var jsonData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as! NSArray

                    //println(jsonData)


                    //convert from JSON into array of dictionaries
                    var rates = [ExchangeRates]()  //instance of class Rate
                    var bnkDct  =  ["bank": "", "currency": "","buyrate": "", "sellrate": ""] //template
                    var indx : Int = 0 //index for iteration

                    for rate in jsonData{
                        let rate = ExchangeRates(rate as! NSDictionary)

                        rates.append(rate)

                            bnkDct["bank"] = rates[indx].bank
                            bnkDct["buyrate"] = rates[indx].buyRate
                            bnkDct["sellrate"] = rates[indx].sellRate
                            bnkDct["currency"] = rates[indx].currency

                        self.bankDict.append(bnkDct)
                        indx += 1
                }

                //println(self.bankDict)



                //Store data in file
                //File path and name
                if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
                        let dir = dirs[0] //documents directory
                        let filePath = dir.stringByAppendingPathComponent("JSONFromServer.txt");

                    NSKeyedArchiver.archiveRootObject(self.bankDict, toFile: filePath)
                   // println(filePath)
                    }


            }
        }

        task.resume()
    }
}

1 个答案:

答案 0 :(得分:1)

您的loadJson函数将完成处理程序作为参数,但您的loadJson函数在完成时不会调用它。先解决这个问题。

然后在viewDidLoad函数中,在调用loadJson时传入完成处理程序。您提供的完成代码是您应该阅读和处理loadJson保存的文件的位置。