Object ***********/******.jpg doesn't exist, Firebase Storage - ios

My problem is when I run the application, this error appears in the console
Optional ("Users Profile / Kk1kKMF89BH778vgd788ju7.jpg does not exist.")
But the file exists in my Firebase storage. I try to download the image to a UIImage named phSelfie.
This is my code:
import UIKit
import Firebase
class SeeSelfieViewController: UIViewController {
var storage = FIRStorage.storage()
#IBOutlet var phSelfie: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let gsRef = storage.reference(forURL: "gs://******-****.appspot.com/profileUsers/")
let user = FIRAuth.auth()!.currentUser!
let imageRef = gsRef.child("\(user.uid).jpg")
imageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
if error != nil {
print("\(error?.localizedDescription)") <------ This run the error!!
} else {
let imageSelfie = UIImage(data: data!)
self.phSelfie.image = imageSelfie
print("Succes")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

I see a few issues:
storage.reference(forURL: "gs://******-****.appspot.com/profileUsers/") should be an HTTP URL, or you should just use storage.reference().child("profileUsers")
Users Profile / Kk1kKMF89BH778vgd788ju7.jpg seems to have spaces in the object, which would be percent escaped %20 in the actual object name.
Users Profile seems to not match profileUsers, which is what the object name above says...

// Press Upload Button Action
#IBAction func uploadButton(_ sender: Any) {
print("Upload Button pressed")
// Create a root reference
let storage = Storage.storage()
let storageReferance = storage.reference()
let mediaFolder = storageReferance.child("media")
print("Media Folder Created")
if let data = UIImageView.image?.jpegData(compressionQuality: 0.5) {
print("Image Selected")
let imageReference = mediaFolder.child("image.jpg")
imageReference.putData(data, metadata: nil) { (metadata,error) in
if error != nil {
print(error?.localizedDescription)
print("Image selection error")
}else{
imageReference.downloadURL { url, error in
if error == nil{
let imageURL = url?.absoluteString
print("Image selection SUCCESS")
print(imageURL)
}
}
}
}
}
}

Related

how to save UIImage to UserDefaults in swift 5 [duplicate]

This question already has answers here:
Save images in NSUserDefaults?
(13 answers)
Closed 9 months ago.
I'm trying to save users image to userDefaults but i'm always getting error "Thread 1: "Attempt to insert non-property list object (Function) for key savedimage" Here's my code
import UIKit
class productSelectionPage: UIViewController {
#IBOutlet weak var productImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Save image
let image = UIImage(named: "user")
let imageData = UIImage.jpegData(image)
UserDefaults.standard.setValue(imageData, forKey: "savedImage")
}
#IBAction func offerButtonTapped(_ sender: UIButton) {
// present image
let imageData = UserDefaults.standard.object(forKey: "savedImage")
let image = UIImage(data: (imageData as! NSData) as Data)
productImageView.image = image
// crash
}
}
Try to use PropertyListEncoder() and Decoder like this:
func saveImage() {
guard let data = UIImage(named: "image").jpegData(compressionQuality: 0.5) else { return }
let encoded = try! PropertyListEncoder().encode(data)
UserDefaults.standard.set(encoded, forKey: "KEY")
}
func loadImage() {
guard let data = UserDefaults.standard.data(forKey: "KEY") else { return }
let decoded = try! PropertyListDecoder().decode(Data.self, from: data)
let image = UIImage(data: decoded)
}
If you have ever used firebase, you would understand that all images and videos are saved as data, not as pixels.
A similar approach is taken when saving to UserDefaults
// storing the image data
private func store(image: UIImage, forKey key: String, withStorageType storageType: StorageType) {
if let pngRepresentation = image.pngData() {
UserDefaults.standard.set(pngRepresentation, forKey: key)
}
}
// retrieving the image data and getting an image
To retrieve it, we will take that image data
private func retrieveImage(forKey key: String, inStorageType storageType: StorageType) -> UIImage? {
if let imageData = UserDefaults.standard.object(forKey: key) as? Data,
let image = UIImage(data: imageData) {
return image
}
}
}
You can just simply convert Image into Data as shown in the extension for UIImageView like below code
//MARK: -|||-To Store Image in Userdefault You can just Simply create an uiimageview extension-||| -
extension UIImageView{
func saveImage(){
guard let image = self.image, let data = image.jpegData (compressionQuality: 0.5) else { return }
let encoded = try! PropertyListEncoder ().encode (data)
UserDefaults.standard.set(encoded, forKey: "image")
}
func loadImage() {
guard let data = UserDefaults.standard.data(forKey: "image") else { return }
let decoded = try! PropertyListDecoder().decode(Data.self, from: data)
let image = UIImage(data: decoded)
self.image = image
}
}
Here is how to use this extension:
class ViewController: UViewController {
#IBOutlet var sendImg: UIImageView!
#IBOutlet var receiveImg: UlImageView!
override func viewDidLoad(){
super.viewDidLoad() {
sendImg.saveImage()
}
#IBAction func loadImageFromUserDefault(_ sender: UIButton) {
receiveImg.loadImage()
}
}
to save image in UserDefault:
yourImage.saveImage()
to get image from UserDefault:
yourImage.loadImage()

Index related error in retrieving the data from Firestore database

I am not able to load the documents in chat application in Swift IOS using Firestore database, though able to successfully retrieve the data from the Firestore database, I have added the deinit method as well please assist further to resolve the error, I have added the complete view controller , please help me
Error
'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (47) must be equal to the number of rows contained in that section before the update (23), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Code
let kBannerAdUnitID = "ca-app-pub-3940256099942544/2934735716"
#objc(FCViewController)
class FCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Instance variables
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var sendButton: UIButton!
var ref : CollectionReference!
var ref2: DocumentReference!
var messages: [DocumentSnapshot]! = []
var msglength: NSNumber = 10
fileprivate var _refHandle: CollectionReference!
var storageRef: StorageReference!
var remoteConfig: RemoteConfig!
private let db = Firestore.firestore()
private var reference: CollectionReference?
private let storage = Storage.storage().reference()
// private var messages = [Constants.MessageFields]()
//snapshot private var messages: [Constants.MessageFields] = []
private var messageListener: ListenerRegistration?
// var db:Firestore!
#IBOutlet weak var banner: GADBannerView!
#IBOutlet weak var clientTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.clientTable.register(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell")
// clientTable.delegate = self
//clientTable.dataSource = self
//db = Firestore.firestore()
ref = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages")
ref2 = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").document()
configureDatabase()
configureStorage()
configureRemoteConfig()
fetchConfig()
loadAd()
}
deinit {
if let refhandle = _refHandle {
let listener = ref.addSnapshotListener { querySnapshot, error in
}
listener.remove()
}
}
func configureDatabase() {
db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
/* let name = documents.map { $0["name"]!}
let text = documents.map { $0["text"]!}
let photourl = documents.map { $0["photoUrl"]!}
print(name)
print(text)
print(photourl)*/
self.messages.append(contentsOf: documents)
// self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
//self.clientTable.reloadData()
}
}
func configureStorage() {
storageRef = Storage.storage().reference()
}
func configureRemoteConfig() {
remoteConfig = RemoteConfig.remoteConfig()
let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)
remoteConfig.configSettings = remoteConfigSettings
}
func fetchConfig() {
var expirationDuration: Double = 3600
// If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
// the server.
if self.remoteConfig.configSettings.isDeveloperModeEnabled {
expirationDuration = 0
}
remoteConfig.fetch(withExpirationDuration: expirationDuration) { [weak self] (status, error) in
if status == .success {
print("Config fetched!")
guard let strongSelf = self else { return }
strongSelf.remoteConfig.activateFetched()
let friendlyMsgLength = strongSelf.remoteConfig["friendly_msg_length"]
if friendlyMsgLength.source != .static {
strongSelf.msglength = friendlyMsgLength.numberValue!
print("Friendly msg length config: \(strongSelf.msglength)")
}
} else {
print("Config not fetched")
if let error = error {
print("Error \(error)")
}
}
}
}
#IBAction func didPressFreshConfig(_ sender: AnyObject) {
fetchConfig()
}
#IBAction func didSendMessage(_ sender: UIButton) {
_ = textFieldShouldReturn(textField)
}
#IBAction func didPressCrash(_ sender: AnyObject) {
print("Crash button pressed!")
Crashlytics.sharedInstance().crash()
}
func inviteFinished(withInvitations invitationIds: [String], error: Error?) {
if let error = error {
print("Failed: \(error.localizedDescription)")
} else {
print("Invitations sent")
}
}
func loadAd() {
self.banner.adUnitID = kBannerAdUnitID
self.banner.rootViewController = self
self.banner.load(GADRequest())
}
// UITableViewDataSource protocol methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue cell
let cell = self.clientTable .dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
// Unpack message from Firebase DataSnapshot
let messageSnapshot: DocumentSnapshot! = self.messages[indexPath.row]
guard let message = messageSnapshot as? [String:String] else { return cell }
let name = message[Constants.MessageFields.name] ?? ""
if let imageURL = message[Constants.MessageFields.imageURL] {
if imageURL.hasPrefix("gs://") {
Storage.storage().reference(forURL: imageURL).getData(maxSize: INT64_MAX) {(data, error) in
if let error = error {
print("Error downloading: \(error)")
return
}
DispatchQueue.main.async {
cell.imageView?.image = UIImage.init(data: data!)
cell.setNeedsLayout()
}
}
} else if let URL = URL(string: imageURL), let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage.init(data: data)
}
cell.textLabel?.text = "sent by: \(name)"
} else {
let text = message[Constants.MessageFields.text] ?? ""
cell.textLabel?.text = name + ": " + text
cell.imageView?.image = UIImage(named: "ic_account_circle")
if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL),
let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage(data: data)
}
}
return cell
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = textField.text else { return true }
textField.text = ""
view.endEditing(true)
let data = [Constants.MessageFields.text: text]
sendMessage(withData: data)
return true
}
func sendMessage(withData data: [String: String]) {
var mdata = data
mdata[Constants.MessageFields.name] = Auth.auth().currentUser?.displayName
if let photoURL = Auth.auth().currentUser?.photoURL {
mdata[Constants.MessageFields.photoURL] = photoURL.absoluteString
}
// Push data to Firebase Database
self.ref.document().setData(mdata, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set newest city data")
}
}
// MARK: - Image Picker
#IBAction func didTapAddPhoto(_ sender: AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
picker.sourceType = .camera
} else {
picker.sourceType = .photoLibrary
}
present(picker, animated: true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let uid = Auth.auth().currentUser?.uid else { return }
// if it's a photo from the library, not an image from the camera
if #available(iOS 8.0, *), let referenceURL = info[.originalImage] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInput(with: nil, completionHandler: { [weak self] (contentEditingInput, info) in
let imageFile = contentEditingInput?.fullSizeImageURL
let filePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\((referenceURL as AnyObject).lastPathComponent!)"
guard let strongSelf = self else { return }
strongSelf.storageRef.child(filePath)
.putFile(from: imageFile!, metadata: nil) { (metadata, error) in
if let error = error {
let nsError = error as NSError
print("Error uploading: \(nsError.localizedDescription)")
return
}
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
})
} else {
guard let image = info[.originalImage] as? UIImage else { return }
let imageData = image.jpegData(compressionQuality:0.8)
let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
self.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
return
}
guard let strongSelf = self else { return }
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
#IBAction func signOut(_ sender: UIButton) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
dismiss(animated: true, completion: nil)
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError.localizedDescription)")
}
}
func showAlert(withTitle title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title,
message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
}
}
}
Edit
perform this block of code on main thread
for doc in documents {
self.messages.append(doc)
self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
}
This should work..

Segue after firebase download/upload completes

Im trying to run some code after firebase has finished its downloading/uploading (eg segue or refresh)
for eg
I have x3 save functions which all have code to update both storage and database of certain data (eg text and images)
save1()
save2()
save3()
when an IBAction is performed I would like these functions to run, and on completion if their is no error to perform another function on completion (segue or refresh)
these 3 save function currently work within the IBAction
#IBAction func saveTap(_ sender: Any) {
save1()
save2()
save3()
}
Save function as follows:
(I check if image has been changed, then upload process begins)
func save1(){
if image1.image == nil {
let gender = userGender.text
self.databaseRef.child("users").child(gender!).child(Auth.auth().currentUser!.uid).child("images").child("imageOne").removeValue { (error, ref) in
if error != nil {
print(error!)}
}
let imageRef = self.storage.child(Auth.auth().currentUser!.uid).child("image1")
imageRef.delete { error in
if let error = error {
print(error)
} else {
print("Photo 1 image deleted")}
}
} else {
//Firebase child references
let profileImageRef = storage.child(Auth.auth().currentUser!.uid).child("image1")
let metaData = StorageMetadata()
metaData.contentType = "image1/jpeg"
//Firebase child references
//change uiimageview to uiimage for upload
guard let image = image1.image else
{return}
//change uiimageview to uiimage for upload
//Send to firebase storage
profileImageRef.putData(image.jpegData(compressionQuality: 0.1)!, metadata: metaData) { (data, error) in
if error == nil
{print("Photo 1 uploaded to storage")}
else
{print(error?.localizedDescription as Any)}}
//Send to firebase storage
//Update firebase database
profileImageRef.downloadURL(completion: { (url, error) in
if error != nil{
print(error!)
return}
if let profilePhotoUrl = url?.absoluteString{
let newValuesForProfile = profilePhotoUrl
let gender = self.userGender.text
self.databaseRef.child("users").child(gender!).child(Auth.auth().currentUser!.uid).child("images").child("imageOne").setValue(newValuesForProfile, withCompletionBlock: { (error, ref) in
if error != nil{
print(error!)
return}
print("Photo 1 updated in database")})}})
//Update firebase database
}
I need the uploads to complete before the segues are performed as the next view will be refreshing to the saved data that i'm trying to upload.
any help would be great, been at this for weeks now :( iv tried completion handlers but no luck as of yet.
thank you in advance
I think dispatchGroup fits with your case
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
save1 { dispatchGroup.leave() }
dispatchGroup.enter()
save2 { dispatchGroup.leave() }
dispatchGroup.notify(queue: .main) {
self.perFormSegue//////
}
//
// e.x structure
func save1(completion:#escaping()->()) {
firesCallBack {
if success {
completion()
}
}
}
You can check if the changes are saved with .childChanged somehow like this:
save1()
save2()
save3()
let ref: DatabaseReference!
ref = /YourDirectDatabaseReferenceForTheChangedNode/
ref.observe(.childChanged, with: {(snaphost) -> Void in
}
})
Maybe you should use UIActivityIndicatorView aswell to show something is going in the background.
#IBAction func saveTap(_ sender: Any) {
save1()
save2()
save3()
let activity: UIActivityIndicatorView = UIActivityIndicatorView()
activity.center = self.view.center
activity.hidesWhenStopped = true
activity.activityIndicatorViewStyle = .whiteLarge
self.view.addSubview(activity)
let ref: DatabaseReference!
ref = /YourDirectDatabaseReferenceForTheChangedNode/
ref.observe(.childChanged, with: {(snaphost) -> Void in
activity.stopAnimating()
if UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.endIgnoringInteractionEvents()
}
self.performSegue(withIdentifier: "backhome", sender: self)
}
})
}
Replace /YourDirectDatabaseReferenceForTheChangedNode/ with the correct child (what should change after save).

Issue uploading an image to firebase storage

I am trying to write a function that will allow a user to set a new profile image, new image will be uploaded and the old image will be removed from firebase storage.
I have two functions that will do this and they work individually, however if I run the upload after the delete function the new image will not upload, even though I get a success message in the console nothing appears in the storage. Ideally I would like to remove first and the set the new image, and I have tried doing this multiple ways; completion handlers, adding delays but nothing has worked. I now even have two buttons one controlling each function to test this but this is still not working. What am I missing?? Any help would be great as ive spent hours racking my brains with this!
Here is my complete code for the VC:
//
// LandingVC.swift
// Login
//
// Created by George Woolley on 07/11/2017.
// Copyright © 2017 George Woolley. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import SwiftKeychainWrapper
import Firebase
class MyAccountVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profilePictureImg: UIImageView!
#IBOutlet weak var usernameField: UILabel!
#IBOutlet weak var saveButton: UIButton!
#IBOutlet weak var changeProfilePicButton: UIButton!
let picker = UIImagePickerController()
let myUID = KeychainWrapper.standard.string(forKey: "uid")
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
if myUID == nil {
print("You are not logged in")
} else {
let ref = DataService.ds.DBCurrentUser
ref.child("MyDetails").observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if snap.key == "username" {
self.usernameField.text = snap.value as? String
}
if snap.key == "profileImageURL" {
if let url = snap.value as? String {
let ref = Storage.storage().reference(forURL: url)
ref.getData(maxSize: 2 * 1024 * 1024, completion: { (data, error) in
if error != nil {
print("An error has occured downloading image")
} else {
print("Image downloaded")
if let imageData = data {
if let img = UIImage(data: imageData) {
self.profilePictureImg.image = img
}
}
}
})
}
}
}
}
})
}
}
func removeImgFromFirebaseStorage() {
let ref = DataService.ds.DBCurrentUser.child("MyDetails")
ref.observe(.value) { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if snap.key == "profileImageURL" {
if let url = snap.value as? String {
let img = Storage.storage().reference(forURL: url)
img.delete(completion: { (error) in
if error != nil {
print("Error is \(String(describing: error))")
} else {
print("Success")
}
})
}
}
}
}
}
saveButton.isHidden = false
changeProfilePicButton.isHidden = true
}
func uploadImageToFirebase() {
if let imageToUpload = profilePictureImg.image {
if let imageData = UIImageJPEGRepresentation(imageToUpload, 0.2) {
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
let imageUID = UUID().uuidString
DataService.ds.StorageProfile.child(imageUID).putData(imageData, metadata: metaData, completion: { (metadata, error) in
if error != nil {
print("Error occured uploading profile image")
} else {
print("Sucess")
if let downloadURL = metadata?.downloadURL()?.absoluteString {
DataService.ds.DBCurrentUser.child("MyDetails").child("profileImageURL").setValue(downloadURL)
}
}
})
}
}
saveButton.isHidden = true
changeProfilePicButton.isHidden = false
}
#IBAction func saveButonPressed(_ sender: Any) {
uploadImageToFirebase()
}
#IBAction func changeProfilePicturePressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePictureImg.contentMode = .scaleAspectFill
profilePictureImg.image = chosenImage
dismiss(animated: true, completion: removeImgFromFirebaseStorage)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
#IBAction func logOffPressed(_ sender: Any) {
KeychainWrapper.standard.removeObject(forKey: "uid")
performSegue(withIdentifier: "loginVC", sender: nil)
let fbLogin = FBSDKLoginManager()
fbLogin.logOut()
try! Auth.auth().signOut()
}
}

NSFileManager.defaultManager().createFileAtPath() returning false

After like a thousand print() statements, I have finally pinpointed the problem! However, I'm not sure how to fix it. The problem lies in the line:
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
According to the Apple Developer's guide, this line of code returns true if the operation was successful or if the item already exists, otherwise false.
This line is returning a false and I'm not exactly sure why because the code preceding the line seems to be okay. Anybody have any suggestions on how to solve this bug?
The rest of the code is here:
//
// ViewController.swift
// Downloading An Image From The Web
//
// Created by Jae Hyun Kim on 9/6/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")
let urlRequest = NSURLRequest(URL: url!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
}
else {
if let bach = UIImage(data: data!) {
//self.image.image = bach
let documentsDirectory:String?
let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.PicturesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
print(paths)
if paths.count > 0 {
documentsDirectory = paths[0] as? String
let savePath = documentsDirectory! + "/bach.jpg"
print(NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil))
if NSFileManager.defaultManager().fileExistsAtPath(savePath) {
print("file available")
}
else {
print("file not available")
}
self.image.image = UIImage(contentsOfFile: savePath)
}
}
}
})
task!.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")!
let urlRequest = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
// you should always do it from the main queue otherwise you will experience a big delay when trying to display your image
dispatch_async(dispatch_get_main_queue()) {
// unwrap your data
if let data = data {
print(data.length)
// get your caches directory URL
let cachesDirectory = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// create your local file url by appending your url last path component
let fileUrl = cachesDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
// save downloaded data to disk
if data.writeToURL(fileUrl, atomically: true) {
print(true)
// load your saved image from disk
self.image.image = UIImage(contentsOfFile: fileUrl.path!)
}
}
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Note you will need to edit your plist as follow:

Resources