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("创建文件") } } } } } } }
···
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。