gpt4 book ai didi

ios - 如何使 UIProgressView 快速工作

转载 作者:行者123 更新时间:2023-11-28 13:07:05 24 4
gpt4 key购买 nike

我正在尝试实现 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)]
}
}

最佳答案

您无法更新进度,因为您没有任何进度。您实现了错误的数据下载方式。使用另一种方式 - 获取委托(delegate)消息的方式。其中之一会告诉您进度。特别是,您将实现

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

这里会把数据累加到一个NSMutableData中,每次都可以把累加的数据大小和期望的总数据大小进行比较,这样就有了更新UIProgressView的依据。

关于ios - 如何使 UIProgressView 快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32387325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com