Swift 下载文件,并读取

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,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("创建文件")
                        }
                    }
                }
            }
        }
    }
}

···

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...