用TextFiled輸入下載地址進行下載


import UIKit

class ViewController: UIViewController,NSURLConnectionDataDelegate {
    var length: CLongLong = 0
    var mData: NSMutableData!
    @IBOutlet var progressView : UIProgressView
    @IBOutlet var TextField : UITextField
    var connection: NSURLConnection!
    @IBAction func didClicked(sender : AnyObject) {
        self.view.endEditing(true)
        var str: NSString = TextField.text
        var url: NSURL = NSURL(string: str)
        var request: NSURLRequest = NSURLRequest(URL: url)
        connection = NSURLConnection(request: request, delegate: self)
        connection.start()
        
    }
   
    @IBAction func didCanceled(sender : AnyObject) {
        connection.cancel()
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        println("connection failed: \(error)")
    }
   
    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!){
        var httpResponse = response as NSHTTPURLResponse
        println("length: \(httpResponse.expectedContentLength)")
        length = httpResponse.expectedContentLength
        
        println("filename: \(httpResponse.suggestedFilename)")
        if httpResponse.statusCode == 200 {
            println("\(httpResponse)")
            mData = NSMutableData()
        }
        else {
            println("失敗")
        }
    }
   
    func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
        mData.appendData(data)
        var progress = Double(mData.length) / Double(length)
        println("receive data: \(progress * 100)%")
        progressView.progress = CGFloat(progress)
    }
   
    func connectionDidFinishLoading(connection: NSURLConnection!) {
        mData.writeToFile("/Users/apple/Desktop/下載文件", atomically: true)
        println("下載完成")
    }
   


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章