Swift 下載檔案,並讀取

kelvinlee發表於2015-03-10

swift 下載圖片並讀取顯示。

····

override func viewDidLoad() {
    super.viewDidLoad()

    var request = HTTPTask()
    let downloadTask = request.download('http://www.test.com/pages_icon_large.png', parameters: nil, progress: {(complete: Double) in
        println(complete)
        }, success: {(response: HTTPResponse) in
            self.downFile(response)
        }, failure: {(error: NSError, response: HTTPResponse?) in
        println("failure")
    })

    var fileManager = NSFileManager.defaultManager()
    var bundleURL = NSBundle.mainBundle().bundleURL
    var contents: NSArray = fileManager.contentsOfDirectoryAtURL(bundleURL, includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil)!
    for URL in contents {
        //println(URL)
    }
    if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
        var enumerator = fileManager.enumeratorAtPath(path)
        println("enumrator: \(path) \(enumerator)")
        while let file: AnyObject = enumerator?.nextObject() {
            println(file)
            if let newPath = NSURL(fileURLWithPath: "\(path)/\(file)") {
                var image = UIImageView(image: UIImage(contentsOfFile: newPath.path!))
                self.view.addSubview(image)
            }
        }
    }


}


func downFile(response: HTTPResponse) {
    if response.responseObject != nil {
        //we MUST copy the file from its temp location to a permanent location.
        if let url = response.responseObject as? NSURL {
            if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
                if let fileName = response.suggestedFilename {
                    if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
                        let fileManager = NSFileManager.defaultManager()
                        println(fileManager.fileExistsAtPath(newPath.path!))
                        if ( fileManager.fileExistsAtPath(newPath.path!) ) {
                            println(newPath)
                            dispatch_async(dispatch_get_main_queue()) {
                                var image = UIImageView(image: UIImage(contentsOfFile: newPath.path!))
                                self.view.addSubview(image)
                                println(image.frame)
                            }
                        }else{
                            fileManager.removeItemAtURL(newPath, error: nil)
                            fileManager.moveItemAtURL(url, toURL: newPath, error: nil)
                            println("建立檔案")
                        }
                    }
                }
            }
        }
    }
}

···

相關文章