简体   繁体   English

迅捷shouldPerformSegueWithIdentifier获取数据异步

[英]swift shouldPerformSegueWithIdentifier get data async

Im making a very basic app which has a search field to get data that is passed to a tableview. 我正在制作一个非常基本的应用程序,该应用程序具有搜索字段来获取传递到表格视图的数据。

What I want to do is run an Async task to get the data and if the data is succesfully fetched go to the next view, during the loading the screen must not freeze thats why the async part is needed. 我想做的是运行一个异步任务来获取数据,如果成功提取了数据,请转到下一个视图,在加载过程中,屏幕一定不要冻结,这就是为什么需要异步部分的原因。

When the user pressed the searchbutton I run the following code to get data in my 当用户按下搜索按钮时,我运行以下代码以获取数据

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {

method. 方法。

    var valid  = true
    let searchValue = searchField.text
    let session = NSURLSession.sharedSession()

    let url = NSURL(string: "https://someapi.com/search?query=" + searchValue!)



    let task = session.dataTaskWithURL(url!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if let theData = data {
            dispatch_async(dispatch_get_main_queue(), {
                //for the example a print is enough, later this will be replaced with a json parser
                print(NSString(data: theData, encoding: NSUTF8StringEncoding) as! String)

            })
        }
        else
        {
            valid =  false;
            print("something went wrong");
        }
    })

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    task.resume()
    return valid;

I removed some code that checks for connection/changes texts to show the app is loading data to make the code more readable. 我删除了一些检查连接/更改文本的代码,以显示应用程序正在加载数据以使代码更具可读性。 This is the part where I have the problem, it comes after all the checks and im sure at this part I have connection etc. 这是我有问题的部分,它是在进行所有检查之后确定的,我确定在此部分我有连接等。

What happens is it returns true (I can see this because the view is loaded), but also logs "Something went wrong" from the else statement. 发生的事情是它返回true(我可以看到这是因为加载了视图),而且还会从else语句中记录“发生了错误”。

I Understand this is because the return valid (at the last line) returns valid before valid is set to false. 我了解这是因为在有效值设置为false之前,返回有效值(在最后一行)返回有效值。 How can I only return true (which changes the view) if the data is succesfully fetched and dont show the next view if something went wrong? 如果成功获取了数据,我怎么才能只返回true(改变视图),如果出了问题,怎么不显示下一个视图?

Because you want the data fetching to be async you cannot return a value, because returning a value is sync (the current thread has to wait until the function returns and then use the value). 因为您希望数据获取是异步的,所以您无法返回值,因为返回值是同步的(当前线程必须等到函数返回后再使用该值)。 What you want instead is to use a callback. 您要使用的是回调。 So when the data is fetched you can do an action. 因此,当获取数据时,您可以执行操作。 For this you could use closures so your method would be: 为此,您可以使用闭包,因此您的方法将是:

func shouldPerformSegue(identifier: String, sender: AnyObject?, completion:(success:Bool) -> ());

And just call completion(true) or completion(false) in your session.dataTaskWithURL block depending on if it was successful or not, and when you call your function you give a block for completion in which you can perform the segue or not based on the success parameter. 只需在session.dataTaskWithURL块中调用completion(true)completion(false) ,具体取决于成功与否,并在调用函数时提供一个completion块,在其中您可以执行segue或不执行success参数。 This means you cannot override that method to do what you need, you must implement your own mechanism. 这意味着您不能override该方法来执行所需的操作,必须实现自己的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM