Xcode9学习笔记74 - 读取和解析Plist属性列表文件(获取远程服务器信息并显示返回数据)
程序员文章站
2024-03-24 09:15:58
...
var label = UILabel()//给当前视图控制器类添加一个标签属性,该标签对象用来显示远程服务器返回的信息
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.frame = CGRect(x: 20, y: 40, width: 280, height: 500)
label.text = "Loading..."//默认文字内容
label.font = UIFont(name: "Arial", size: 12)
label.backgroundColor = UIColor.lightGray
label.numberOfLines = 0//0表示不限制标签对象的行数
label.lineBreakMode = NSLineBreakMode.byWordWrapping
self.view.addSubview(label)
let url = URL(string: "http://www.weather.com.cn/data/sk/101010100.html")
let request = URLRequest.init(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 30)//第2个参数为网络请求的缓存协议
do {
var response:URLResponse?//创建一个网络返回对象
//利用网络连接对象实现网络的通信,网络连接创建成功后,就创建了一个网络连接,并将返回结果存储为一个二进制数据对象
let data:Data? = try NSURLConnection.sendSynchronousRequest(request, returning: &response)
//将数据对象转化成字符串对象并采用指定的编码方式
let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.label.text = str! as String
} catch {
print("Network error.")
}
}