Skip to content

Instantly share code, notes, and snippets.

@davidkneely
Created November 16, 2017 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidkneely/de953c5682de92f2a5a948e2653e7ebc to your computer and use it in GitHub Desktop.
Save davidkneely/de953c5682de92f2a5a948e2653e7ebc to your computer and use it in GitHub Desktop.
//TODO: Make this work
static func saveImageToFirebase(withImage inputImage: UIImage, andPhotoIsForProfile inputPhotoIsForProfile: Bool, andUserId inputUserId: String) {
// Get a reference to the storage service using the default Firebase App
let storage = Storage.storage()
// Create a storage reference from our storage service
let storageRef = storage.reference()
var imageName = ""
let imageType = "png"
if inputPhotoIsForProfile {
imageName = "\(inputUserId)_profile"
} else {
imageName = "\(inputUserId)_background"
}
// saves the image
let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let filePath = "\(docsurl)\(imageName).\(imageType)"
// Convert input image to NSData
let data = UIImagePNGRepresentation(inputImage) as NSData?
guard let imageData: NSData = data else {fatalError()}
// Check if file exists there already
let doesExistAlready = doesFileExistInDocumentsDirectory(withFileName: "\(imageName).\(imageType)")
if doesExistAlready {
// Delete it if it alreay exists
do {
try fm.removeItem(atPath: filePath)
} catch {
//TODO: Fix, it always crashes here.
print("could not remove item")
}
}
// save it with the new one
// check if this is valid image data
// Fails on createFile
if fm.createFile(atPath: filePath, contents: imageData as Data, attributes: nil) {
// gets the path to the saved image
var localFileUrl = docsurl.appendingPathComponent("\(imageName).\(imageType)")
let profileImageRef = storageRef.child("\(imageName).\(imageType)")
// Upload the file to the path "images/rivers.jpg"
profileImageRef.putFile(from: localFileUrl, metadata: nil) { metadata, error in
if let error = error {
// Uh-oh, an error occurred!
print(error.localizedDescription)
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL()
if let catPictureData = NSData(contentsOf: localFileUrl) {
var catPicture = UIImage(data: catPictureData as Data)
//TODO: Set the image in the NavigationController with this image
// NavigationBarController.setProfileLogoutButton(withViewController: inputViewController)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment