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("创建文件")
}
}
}
}
}
}
}
···
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。