我正在尝试实现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)]
}
}
您无法更新进度,因为您没有拥有任何进度。您实现了错误的下载数据的方式。用另一种方式,你获得委托消息的方式。其中一个告诉你进度。特别是,您将实现
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData {
这里你将在NSMutableData中积累数据,每次,你都可以将积累数据的大小与预期的总数据的大小进行比较,因此你有更新UIProgressView的基础。