(作业)使用多线程实现一个网络服务访问程序

又是一个关于多线程的作业,老样子,先看需求
(作业)使用多线程实现一个网络服务访问程序_第1张图片

这次作业具体要做成什么样子没有指定,那我们就做一个加载成都的天气信息吧。
具体的运行效果如下:
(作业)使用多线程实现一个网络服务访问程序_第2张图片

要实现这个功能很简单,首先我们先声明一个显示信息的UITextView

var textView: UITextView!

然后分别将UITextView和一个按钮添加到视图上

self.view.backgroundColor = UIColor.white

let loadButton = UIButton(frame: CGRect(x: 100, y: 100, width: 150, height: 40))
loadButton.setTitle("加载成都天气", for: .normal)
loadButton.setTitleColor(UIColor.cyan, for: .normal)
loadButton.setTitleColor(UIColor.brown, for: .highlighted)
loadButton.addTarget(self, action: #selector(loadImage), for: .touchUpInside)
self.view.addSubview(loadButton)

textView = UITextView(frame: CGRect(x: 10, y: 200, width: 300, height: 300))
textView.font = UIFont.systemFont(ofSize: 44)
textView.layer.borderWidth = 1
self.view.addSubview(textView)

最后再实现按钮的action即可

@objc func loadImage() {
    DispatchQueue.global().async {            
        let url = URL(string: "http://www.weather.com.cn/data/sk/101270101.html")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
            if error == nil {
                if let json = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] {
                    if let dict = json!["weatherinfo"] as? [String: String] {
                        var text = ""
                        text += "城市:" + dict["city"]! + "\n"
                        text += "温度:" + dict["temp"]! + "\n"
                        text += "风向:" + dict["WD"]! + "\n"
                        text += "风力:" + dict["WS"]! + "\n"
                        DispatchQueue.main.async {
                            self.textView.text = text
                        }
                    }
                }
            }
        })
        dataTask.resume()
    }
}

在刚进入这个方法时,我们使用系统设定好的全局队列来加载线程,使用异步的方式加载不会造成界面的卡顿,然后初始化一个URL和URLRequest,这两个变量用于获取json数据。
然后再使用URLSession的单例shared初始化一个URLSession的对象,再调用它的dataTask方法来进行网络获取到的数据的解析。在闭包中,我们将获取到的data以json的格式解析出来,并将最后的结果显示在UITextView中,因为涉及到对界面组件的操作,所以对主界面元素的操作必须放在主线程中。
最后我们需要调用dataTask的resume()方法来开始网络服务。

所有代码如下:

import UIKit

class ViewController: UIViewController {

    var textView: UITextView!

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

        self.view.backgroundColor = UIColor.white

        let loadButton = UIButton(frame: CGRect(x: 100, y: 100, width: 150, height: 40))
        loadButton.setTitle("加载成都天气", for: .normal)
        loadButton.setTitleColor(UIColor.cyan, for: .normal)
        loadButton.setTitleColor(UIColor.brown, for: .highlighted)
        loadButton.addTarget(self, action: #selector(loadImage), for: .touchUpInside)
        self.view.addSubview(loadButton)

        textView = UITextView(frame: CGRect(x: 10, y: 200, width: 300, height: 300))
        textView.font = UIFont.systemFont(ofSize: 44)
        textView.layer.borderWidth = 1
        self.view.addSubview(textView)

    }

    @objc func loadImage() {
        DispatchQueue.global().async {
            let url = URL(string: "http://www.weather.com.cn/data/sk/101270101.html")
            let request = URLRequest(url: url!)
            let session = URLSession.shared
            let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
                if error == nil {
                    if let json = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] {
                        if let dict = json!["weatherinfo"] as? [String: String] {
                            var text = ""
                            text += "城市:" + dict["city"]! + "\n"
                            text += "温度:" + dict["temp"]! + "\n"
                            text += "风向:" + dict["WD"]! + "\n"
                            text += "风力:" + dict["WS"]! + "\n"
                            DispatchQueue.main.async {
                                self.textView.text = text
                            }
                        }
                    }
                }
            })
            dataTask.resume()
        }
    }

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

你可能感兴趣的:(Swift)