Procházet zdrojové kódy

Images downloaded from server.

Iñigo Valentin před 9 roky
rodič
revize
6d3d914a91
1 změnil soubory, kde provedl 48 přidání a 3 odebrání
  1. 48 3
      app/UIImageView.swift

+ 48 - 3
app/UIImageView.swift

@@ -40,14 +40,59 @@ extension UIImageView {
 		let filePath = url.appendingPathComponent(localPath)?.path
 		let fileManager = FileManager.default
 		if fileManager.fileExists(atPath: filePath!) {
-			print("FILE AVAILABLE: \(filePath)")
+			print("IMAGE:LOG: File available: \(filePath)")
 			//TODO Set image
 			return 0
 		} else {
-			print("FILE NOT AVAILABLE: \(filePath)")
-			print("Downloading from \(remotePath)")
+			print("IMAGE:LOG: File not available: \(filePath)")
+			print("IMAGE:LOG: Downloading from \(remotePath)")
 			//TODO Download
 			//TODO Set image
+			
+			//Create required directories
+			var fileFolderUrl = URL(fileURLWithPath: filePath!)
+			fileFolderUrl.deleteLastPathComponent()
+			print("IMAGE:DEBUG: Creating folder \(fileFolderUrl)")
+			do{
+				try fileManager.createDirectory(at:  fileFolderUrl, withIntermediateDirectories: true, attributes: nil)
+			}
+			catch(let error){
+				print("IMAGE:ERROR: Error creating directories at \(fileFolderUrl.path): \(error.localizedDescription)")
+			}
+			
+			// Create destination URL
+			let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
+			//let destinationFileUrl = URL(string: filePath!)//documentsUrl.appendingPathComponent("downloadedFile.jpg")
+			let destinationFileUrl = URL(fileURLWithPath: filePath!)
+			
+			//Create URL to the source file you want to download
+			let fileURL = URL(string: remotePath)
+			
+			let sessionConfig = URLSessionConfiguration.default
+			let session = URLSession(configuration: sessionConfig)
+			
+			let request = URLRequest(url:fileURL!)
+			
+			let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
+				if let tempLocalUrl = tempLocalUrl, error == nil {
+					// Success
+					if let statusCode = (response as? HTTPURLResponse)?.statusCode {
+						print("IMAGE:LOG: Successfully downloaded. Status code: \(statusCode)")
+					}
+					
+					do {
+						try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
+					} catch (let writeError) {
+						print("IMAGE:ERROR: Error creating a file \(destinationFileUrl) : \(writeError)")
+					}
+					
+				} else {
+					print("IMAGE:ERROR: Error took place while downloading a file: %@", error?.localizedDescription);
+				}
+			}
+			task.resume()
+		
+		
 			return 1
 		}