在线数据加载时暂停Swift代码执行?

时间:2017-01-16 16:57:16

标签: ios mysql swift

我正在为教会制作一个简单的应用程序,该教会从成员的MySQL数据库中检索随机名称并设置"检索名称"按钮文本到成员名称。它主要工作,但按钮的第一次点击不会更改按钮文本,虽然打印显示它正在从数据库中正确检索名称。当我反复点击时,有时文本会发生变化,有时候它不会发生变化。我认为这可能是因为数据尚未加载而且Swift过快地进入下一段代码。有没有一种正确的方法来延迟这个,直到数据加载?谢谢!

以下是应用代码:

//
//  ViewController.swift
//  Grace Tabernacle Prayer App
//
//  Created by Nico Pampaloni on 1/14/17.
//  Copyright © 2017 Pampaloni Code. All rights reserved.
//
// Simple app to retrieve a random name from a MySQL database and    display that name as the button text.


import UIKit

class ViewController: UIViewController {



    @IBAction func buttonPressed(_ sender: UIButton) {
        // set URL of php script as NSURL
        let scriptUrl = "https://gtinternal.com/api/getname.php"
        let myUrl = NSURL(string: scriptUrl);
        let request = NSMutableURLRequest(url:myUrl! as URL);
        // use HTTP GET to retreive request data
        request.httpMethod = "GET"

        // store the GET response and convert to a String
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

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

            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!

            let memberName = responseString as String

            print(responseString)

            // change Button text to retrieved string
            sender.setTitle(memberName, for: .normal)
        }

        task.resume()  
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1 个答案:

答案 0 :(得分:0)

这里的问题是任务内部的代码作为闭包块的一部分异步执行。这意味着它没有在主线程上运行。然后,您尝试从后台线程更新UI,这将产生意外结果。始终将您的UI代码放在主线程上。当您在$file = ParseFile::createFromFile("imagePath.jpg", "image.jpg", "image/jpg"); $file->save(); try { $query = new ParseQuery("_User"); $query->equalTo("username", "myUsername"); $results = $query->find($useMasterKey = true); foreach($results as $user) { $user->set('email','me@myEmail.com'); $user->set('profilePic', $file); $user->save($useMasterKey = true); } } catch (ParseException $error) { echo 'Error message: '.$error->getMessage(); } 上设置标题时,将该代码放在一个块中以在主线程上执行。

...

sender

...