iOS   发布时间:2022-05-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何将文件下载链接到进度视图大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我的下面的按钮代码从URL下载文件,我需要将其与进度视图链接以显示下载进度. @IBACtion func btnStream(sender: UIButton) { // First you need to create your audio url if let audioUrl = NSURL(String: "http://website.com/file.mp3")
我的下面的按钮代码从URL下载文件,我需要将其与进度视图链接显示下载进度.

@IBACtion func btnStream(sender: UIButton) {

    //  First you need to create your audio url

    if let audioUrl = NSURL(String: "http://website.com/file.mp3") {

        // then lets create your document folder url
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask).first as! NSURL

        // lets create your desTination file url
        let desTinationUrl = documentsUrl.URLByAppendingPathComponent(audioUrl.lastPathComponent!)
        println(desTinationUrl)
        // to check if it exists before downloading it
        if NSFileManager().fileExistsAtPath(desTinationUrl.path!) {
            println("The file already exists at path")

            // if the file doesn't exist
        } else {

            //  just download the data from your url
            if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
                // after downloading your data you need to save it to your desTination url
                if myAudioDataFromUrl.writeToURL(desTinationUrl,atomically: truE) {
                    println("file saved")
                } else {
                    println("error saving file")
                }
            }
        }
    }

}

如何将我的下载进度与Swift中的Progress View链接

解决方法

以下是完整的工作示例:

import UIKit

class ViewController: UIViewController,NSURLSessionDownloadDelegate {


    @IBOutlet weak var progressBar: UIProgressview!
    @IBOutlet weak var progressCount: UILabel!

    var task : NSURLSessionTask!

    var percentageWritten:Float = 0.0
    var task@R_856_10586@lBytesWritten = 0
    var task@R_856_10586@lBytesExpectedToWrite = 0

    lazy var session : NSURLSession = {
        let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        config.allowsCellularAccess = false
        let session = NSURLSession(configuration: config,delegate: self,delegateQueue: NSOperationQueue.mainQueue())
        return session
        }()

    override func viewDidLoad() {
        progressBar.setProgress(0.0,animated: truE)  //set progressBar to 0 at start
    }

    @IBACtion func doElaboratehttp (sender:AnyObject!) {

        progressCount.text = "0%"
        if self.task != nil {
            return
        }

        let s = "http://www.qdtricks.com/wp-content/uploads/2015/02/hd-wallpapers-1080p-for-mobile.png"
        let url = NSURL(String:s)!
        let req = NSMutableURLrequest(URL:url)
        let task = self.session.downloadTaskWithrequest(req)
        self.task = task
        task.resume()

    }

    func URLSession(session: NSURLSession,downloadTask: NSURLSessionDownloadTask,didWriteData bytesWritten: Int64,@R_856_10586@lBytesWritten writ: Int64,@R_856_10586@lBytesExpectedToWrite exp: Int64) {
        println("downloaded \(100*writ/exp)")
        task@R_856_10586@lBytesWritten = Int(writ)
        task@R_856_10586@lBytesExpectedToWrite = Int(exp)
        percentageWritten = Float(task@R_856_10586@lBytesWritten) / Float(task@R_856_10586@lBytesExpectedToWritE)
        progressBar.progress = percentageWritten
        progressCount.text = String(format: "%.01f",percentageWritten*100) + "%"
    }

    func URLSession(session: NSURLSession,didResumeAtOffset fiLeoffset: Int64,expected@R_856_10586@lBytes: Int64) {
        // unused in this example
    }

    func URLSession(session: NSURLSession,task: NSURLSessionTask,didCompleteWithError error: NSError?) {
        println("completed: error: \(error)")
    }

    // this is the only required NSURLSessionDownloadDelegate method

    func URLSession(session: NSURLSession,didFinishDownloadingToURL LOCATIOn: NSURL) {

        let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask).first as! NSURL
        println("Finished downloading!")
        println(documentsDirectoryURL)
        var err:NSError?

        // Here you can move your downloaded file
        if NSFileManager().moveItemAtURL(LOCATIOn,toURL: documentsDirectoryURl.URLByAppendingPathComponent(downloadTask.response!.suggestedFilename!),error: &err) {
            println("File saved")
        } else {
            if let err = err {
                println("File not saved.\n\(err.description)")

            }
        }

    }

}

您可以使用NSURLSessionDownloadDelegate来实现此方法,在用户下载数据时将调用方法.

这将显示进入progressCount标签的进程,progressBar将显示进程,因为count将递增.你可以根据需要修改它.

您可以从HERE下载此示例.

大佬总结

以上是大佬教程为你收集整理的ios – 如何将文件下载链接到进度视图全部内容,希望文章能够帮你解决ios – 如何将文件下载链接到进度视图所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。