Swift JSON解析避免每个视图的方法声明

时间:2015-03-04 22:26:54

标签: ios json swift xcode6

我正在从json获取数据并将其操作到表视图中,但问题是我有很多视图,大约5-6,每个视图都有单独的类,并且在每个类中我声明相同JSON解析方法一次又一次,我怎样才能避免这种重复?我想在AppDelegate中将该方法声明为类方法,但我遇到了一个问题:

在返回json之后,我会在另一个函数中使用它来提取数据,但是我在这里遇到了这个错误。请帮忙!如果有更好的方法我想知道。 谢谢

更新

class func get_data_from_url(url:String) -> NSString
    {
        var json:NSString?
        let url = NSURL(string: url)
        let urlRequest = NSMutableURLRequest(URL: url!,
            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
            timeoutInterval: 15.0)
        let queue = NSOperationQueue()
        NSURLConnection.sendAsynchronousRequest(
            urlRequest,
            queue: queue,
            completionHandler: {(response: NSURLResponse!,
                data: NSData!,
                error: NSError!) in
                if data == nil {
                    dispatch_async(dispatch_get_main_queue(), {
                        let alert = UIAlertView()
                        alert.title = "Connection Error"
                        alert.message = "Could not connect to the server"
                        alert.addButtonWithTitle("Ok")
                        alert.show()
                    });
                }
                else {
                    if data.length > 0 && error == nil{
                        json = NSString(data: data, encoding: NSASCIIStringEncoding)
                    }else if data.length == 0 && error == nil{
                        println("Nothing was downloaded")
                        return
                    } else if error != nil{
                        println("Error happened = \(error)")
                        return
                    }
                }
            }
        )
        return json!
    }

我在最后一行收到错误,“返回json!” - > “致命错误:在打开可选值时意外发现nil”

任何建议?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:你的ClassB是加载json的地方,所以从A类开始,你调用方法loadJson,当在B类中下载json时,你将json发送回A类:

    //Class A :
    ClassB.loadJson{ (success, json) -> Void in
        if (success) //... you use the json
        //println("receive json from Class B, use it here")
        return
    }

    //ClassB
    typealias OnComplete = (Bool, NSString) -> ()

    class func loadJson(completion:OnComplete){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
            //json = ... load your json here
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                println("json loaded")
                completion(true, json) //send result back to Class A
            })//main
    }