使用回调从调用数据库获取JSON值 [英] Use callback to get JSON value from call to database

查看:127
本文介绍了使用回调从调用数据库获取JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用json结果填充UITable.我调用了一个从服务器获取json并将结果存储在NSDictionary中的函数.我希望能够使用此集合,然后填充一个表.但是,我遇到了一个问题,因为对于func numberOfRowsInSection,我需要集合的计数,并且由于我的json结果位于try/catch内的另一个函数中,所以我似乎无法返回该值.

I am trying to populate a UITable with a json result. I call a function that gets the json from the server and stores the result in NSDictionary. I want to be able to use this collection, and then populate a table. I run into a problem however because for the func numberOfRowsInSection I need the count of the collection, and since my json result is within another function inside a try/catch I cant seem to return the value.

这就是我在ViewDidLoad()中调用的函数所需要的:

This is what I have for the function which I call in ViewDidLoad():

func getSubjects() -> NSDictionary{

    let myUrl = NSURL(string: "www.mydomain.com/script.php");
    let request = NSMutableURLRequest(url:myUrl as! URL)
    let user_id = UserDetails[0]

    request.httpMethod = "POST";
    let postString = "user_id=\(user_id)";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request as URLRequest){

        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        var err: NSError?
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {

                let resultValue: NSDictionary = parseJSON["subjects"] as! NSDictionary

            }

        } catch let error as NSError {
            err = error
            print(err!);
        }
    }
    task.resume();
}

如果我打印resultValue,我将得到所需的东西,在此示例中为:

If I print resultValue I get what I need, in this example being:

{
1 =     (
    Maths,
    Lecture
);
2 =     (
    Science,
    Lecture
);
3 =     (
    English,
    Seminar
);

}

但是,令人困惑的是,我该如何返回该值?在哪里?以及如何在表格中实现它?如果我在解析JSON时尝试返回resultValue,则会收到错误消息,提示它是unexpected non-void return in void function,并且如果我尝试在函数末尾返回值,则会得到unresolved identifier error

But the confusion is, how do I go about returning this value? and where? and how would I implement it in the table? If I try to return resultValue when I parse the JSON I get the error that it is unexpected non-void return in void function and if I try to return the value at the end of the function, I get an unresolved identifier error

我觉得我的实现方式不正确.我已经检查了很多教程,似乎没有人用POST JSON填充表,所以我不知道如何返回值或正确的实现方法.任何帮助将不胜感激!

I feel I am implementing this incorrectly. I have checked many tutorials on this, and no one seems to populate a table with a POST JSON so I don't know how to go about returning the value, or the proper method of implementation. Any help would be greatly appreciated!

推荐答案

您遇到的问题是,在尝试返回字典时尚未检索到该字典.从数据库中检索字典后,可以使用异步回调来获取字典.

The problem your having is that the dictionary hasn't been retrieved by the time you try to return it. You can use an asynchronous callback to get the dictionary after it has been retrieved from your database.

func getSubjects(callback: @escaping (NSDictionary)-> Void){

let myUrl = NSURL(string: "www.mydomain.com/script.php");
let request = NSMutableURLRequest(url:myUrl as! URL)
let user_id = UserDetails[0]

request.httpMethod = "POST";
let postString = "user_id=\(user_id)";
request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request as URLRequest){

    data, response, error in

    if error != nil {
        print("error=\(error)")
        return
    }

    var err: NSError?
    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

        if let parseJSON = json {

            let resultValue: NSDictionary = parseJSON["subjects"] as! NSDictionary

            callback(resultValue)

        }

    } catch let error as NSError {
        err = error
        print(err!);
    }
}
task.resume();
}

然后您将调用此函数,如...

and then you would call this function like...

getSubjects(callback: {(resultValue)-> Void in 
    print(resultValue)
    //here you could set your tableView data equal to the values in the dictionary that was just received and then call self.tableView.reloadData to update your table view
})

因此,也许在您的UITableViewController的viewDidLoad()函数中或在viewDidAppear(_:)中,根据视图的生命周期,您将像上面显示的那样调用getSubjects(...),然后在调用回调时调用如我在函数调用中所述,self.tableView.reloadData().如果不确定如何设置tableview数据源和委托,那么您可能应该为此提出另一个问题

So perhaps in the viewDidLoad() function of you UITableViewController or in the viewDidAppear(_:), depending on the life cycle of your view, you would call getSubjects(...) as i have shown above and then when the callback is called you call self.tableView.reloadData() as I have explained in the function call. If you are unsure how to setup a tableview datasource and delegate then you should probably open another question for that

编辑 为了回应您的评论,询问如何将服务器中检索到的值用作整个类可用的变量,您可以执行以下操作...

EDIT In response to your comment asking how to use the retrieved value from your server as a variable available to your whole class, you could do something like this...

class: ExampleViewController {
    var resultsDictionary: [Int: [String: String]]?

    override func viewDidLoad(){
        getSubjects(callback: {(resultValue)-> Void in 
            resultsDictionary = resultValue
        })
    }

    //Use the actual getSubjects function I have already shown you above
    func getSubjects(){...}


}

这篇关于使用回调从调用数据库获取JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆