ios - Web 服务值未出现在标签中

标签 ios mysql json swift

我不知道为什么这不起作用。我有一个从 MYSQL 数据库中提取名称和标题的 Web 服务。它的工作。我什至添加了一个打印语句来测试 JSON 结果和我的 html 格式的字符串。出于某种原因,当我把它写到标签上时,它什么也没显示。任何帮助将不胜感激。下面是完整的代码。

import UIKit

class ContactsViewController: UIViewController {

    @IBOutlet weak var contactsLabel: UILabel!
    //Our web service url
    let URL_GET_TEAMS:String = "http://www.example.com/apps/getcontacts.php"

    var myLabel : String = ""

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


        //created NSURL
        let requestURL = NSURL(string: URL_GET_TEAMS)


        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)

        //setting the method to post
        request.httpMethod = "GET"

        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in

            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                var teamJSON: NSDictionary!
                teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                //getting the JSON array teams from the response
                let teams: NSArray = teamJSON["contacts"] as! NSArray

                //looping through all the json objects in the array teams
                for i in 0 ..< teams.count{

                    //getting the data at each index
                    let teamId:String = (teams[i] as! NSDictionary)["title"] as! String!
                    let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String!



                    //displaying the data
                    print("id -> ", teamId)
                    print("name -> ", teamName)
                    print("===================")
                    print("")
                    self.myLabel = self.myLabel + "<font size='5'><b>" + teamId + "</font>:</b> " + "<font size='5'>" + teamName + "</font><br /><br />"
                    print(self.myLabel)
                }

            } catch {
                print(error)
            }
        }
        //executing the task
        task.resume()

        let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        contactsLabel.attributedText = attrStr
        contactsLabel.sizeToFit()
    }

 }

最佳答案

URLSession 在异步的后台线程中运行,因此您必须返回闭包中的主线程。

import UIKit

class ContactsViewController: UIViewController {

    @IBOutlet weak var contactsLabel: UILabel!
    //Our web service url
    let URL_GET_TEAMS:String = "http://www.example.com/apps/getcontacts.php"

    var myLabel : String = ""

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


        //created NSURL
        let requestURL = NSURL(string: URL_GET_TEAMS)


        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)

        //setting the method to post
        request.httpMethod = "GET"

        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in

            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                var teamJSON: NSDictionary!
                teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                //getting the JSON array teams from the response
                let teams: NSArray = teamJSON["contacts"] as! NSArray

                //looping through all the json objects in the array teams
                for i in 0 ..< teams.count{

                    //getting the data at each index
                    let teamId:String = (teams[i] as! NSDictionary)["title"] as! String!
                    let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String!



                    //displaying the data
                    print("id -> ", teamId)
                    print("name -> ", teamName)
                    print("===================")
                    print("")
                    self.myLabel = self.myLabel + "<font size='5'><b>" + teamId + "</font>:</b> " + "<font size='5'>" + teamName + "</font><br /><br />"
                    print(self.myLabel)
                }

            } catch {
                print(error)
            }

            DispatchQueue.main.async {
                let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
                contactsLabel.attributedText = attrStr
                contactsLabel.sizeToFit()
            }
        }
        //executing the task
        task.resume()
    }

 }

当您调用 resume() 时,任务在后台运行,因此标签会立即更新,而文本仍未更改。这是一个常见但令人困惑的错误——请记住 dataTask 在后台线程中运行,因此请在其闭包内更新 UI。

关于ios - Web 服务值未出现在标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44070419/

相关文章:

ios - UIImagePickerController 保存带有地理位置信息的图像?

php - 如何通过id显示?代码点火器

javascript - 在 NodeJS Express 中返回带有嵌套数组的 JSON 数据和标题

javascript - 从 JSON 数组中删除元素

ios - XXX 不支持 Azure 构建管道中的配置文件

ios - 等到 scrollToRowAtIndexPath swift 完成

ios - Restkit 在嵌套外键关系中使用@parent

php - 您可以从 mysqli 对象获取连接数据吗?

mysql - AWS RDS 错误 2003

angularjs - 当 ng-hide 在 2 个表之间分割时, Angular 奇数、偶数不起作用