如何使UIProgressView在swift中工作

时间:2015-09-04 00:13:41

标签: ios xcode swift

我正在尝试实施UIProgressView!。我正在从网站下载一些数据,而我并没有围绕如何编写此代码的一些基础知识。我有一个名为message的标签,它将在下载数据时更新,但我想显示正在下载的数据的进度。

import UIKit

class ViewController: UIViewController {

    //They user types in the city they want to recieve the weather from
    @IBOutlet weak var city: UITextField!

    //The label that is being updated when the data finally reaches the phone
    @IBOutlet weak var message: UILabel!

    //The progress bar
    @IBOutlet weak var downloadProgress: UIProgressView!

    //My 'What's the weather?' button
    @IBAction func buttonPressed(sender: AnyObject) {

        //When you touch the button, the keyboard goes away
        self.view.endEditing(true)

        //setting the urlString to the address of the website, it will add the city that you type into the city text field
        var urlString = "http://www.weather-forecast.com/locations/" + city.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"

        //Setting the url to the urlString
        var url = NSURL(string: urlString)

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!){(data, response, error) in

            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) 
            var contentArray  = urlContent!.componentsSeparatedByString("<span class=\"phrase\">")
            var newContentArray = contentArray[1].componentsSeparatedByString("</span>")

            //Updating the message text with the content that I want from the HTML source
            self.message.text = (newContentArray[0] as! String) 
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

self.downloadProgress.progress = 0.0

    }

    func makeMyProgressBarMoving {

        var recievedData : Float
        var expectedTotalSize : Float
        var actual : Float = downloadProgress.progress
        if (actual < 1) {
            downloadProgress.progress = actual + (recievedData/expectedTotalSize)
            [NSTimer .scheduledTimerWithTimeInterval(0.05, invocation: self, repeats: false)]
        }   
    }

1 个答案:

答案 0 :(得分:2)

您无法更新进度,因为您没有任何进展。您已经实施了错误的下载数据方式。使用另一种方式 - 您获得委托消息的方式。其中一个告诉你进展情况。特别是,您将实施

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData {

在这里,您可以在NSMutableData中累积数据,每次都可以将累积数据的大小与预期的总数据大小进行比较,从而获得更新UIProgressView的基础。 / p>