Swift 下载文件,并读取

前端之家收集整理的这篇文章主要介绍了Swift 下载文件,并读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

swift 下载图片并读取显示

····

  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3.  
  4. var request = HTTPTask()
  5. let downloadTask = request.download('http://www.test.com/pages_icon_large.png',parameters: nil,progress: {(complete: Double) in
  6. println(complete)
  7. },success: {(response: HTTPResponse) in
  8. self.downFile(response)
  9. },failure: {(error: NSError,response: HTTPResponse?) in
  10. println("failure")
  11. })
  12.  
  13. var fileManager = NSFileManager.defaultManager()
  14. var bundleURL = NSBundle.mainBundle().bundleURL
  15. var contents: NSArray = fileManager.contentsOfDirectoryAtURL(bundleURL,includingPropertiesForKeys: nil,options: .SkipsPackageDescendants,error: nil)!
  16. for URL in contents {
  17. //println(URL)
  18. }
  19. if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).first as? String {
  20. var enumerator = fileManager.enumeratorAtPath(path)
  21. println("enumrator: \(path) \(enumerator)")
  22. while let file: AnyObject = enumerator?.nextObject() {
  23. println(file)
  24. if let newPath = NSURL(fileURLWithPath: "\(path)/\(file)") {
  25. var image = UIImageView(image: UIImage(contentsOfFile: newPath.path!))
  26. self.view.addSubview(image)
  27. }
  28. }
  29. }
  30.  
  31.  
  32. }
  33.  
  34.  
  35. func downFile(response: HTTPResponse) {
  36. if response.responSEObject != nil {
  37. //we MUST copy the file from its temp location to a permanent location.
  38. if let url = response.responSEObject as? NSURL {
  39. if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,true).first as? String {
  40. if let fileName = response.suggestedFilename {
  41. if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
  42. let fileManager = NSFileManager.defaultManager()
  43. println(fileManager.fileExistsAtPath(newPath.path!))
  44. if ( fileManager.fileExistsAtPath(newPath.path!) ) {
  45. println(newPath)
  46. dispatch_async(dispatch_get_main_queue()) {
  47. var image = UIImageView(image: UIImage(contentsOfFile: newPath.path!))
  48. self.view.addSubview(image)
  49. println(image.frame)
  50. }
  51. }else{
  52. fileManager.removeItemAtURL(newPath,error: nil)
  53. fileManager.moveItemAtURL(url,toURL: newPath,error: nil)
  54. println("创建文件")
  55. }
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }

···

猜你在找的Swift相关文章