我不知道为什么这不起作用。我有一个Web服务,从MYSQL数据库中提取名称和标题。它的工作。我甚至添加了一个print语句来测试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()
}
}
答案 0 :(得分:1)
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
在后台线程中运行,因此更新其clousure中的UI。