Downloading image on Swift 2 form Firebase Storage - firebase

Whenever I download an image from Firebase Storage it download's perfectly, but once I try to change the imageview "my" to it, the imageview disappears. I don't have constraints and I navigated to the local URL and found the image perfectly there. Any help? Am I doing something wrong?
func loadImages(){
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let newRef = storageRef!.child("Images/0.jpg")
let fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("p.jpg")
let downloadTask = newRef.writeToFile(fileDestinationUrl){ (URL, error) -> Void in
if (error != nil) {
print("problem")
} else {
print("done")
}
}
downloadTask.observeStatus(.Success) { (snapshot) -> Void in
print(fileDestinationUrl)
var temp = String(fileDestinationUrl)
print(temp)
var my = UIImage(contentsOfFile: temp)
self.image.image = my
}
}

Print the destinationUrl in your console .Go to your downloaded file location , open your terminal , drag and drop the DOWNLOADED image in the terminal and the terminal will give you its actual path.Now compare both the path the one that terminal gave you and the one that console gave you, match those. most like they are to be different ,change them accordingly.
Example code :-
Uploading Code : -
func profilePictureUploading(infoOnThePicture : [String : AnyObject],completionBlock : (()->Void)) {
if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {
print(referenceUrl)
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as! NSURL], options: nil)
print(assets)
let asset = assets.firstObject
print(asset)
asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (ContentEditingInput, infoOfThePicture) in
let imageFile = ContentEditingInput?.fullSizeImageURL
print("imagefile : \(imageFile)")
let filePath = FIRAuth.auth()!.currentUser!.uid + "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))/\(imageFile!.lastPathComponent!)"
print("filePath : \(filePath)")
FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: { (metadata, error) in
if error != nil{
print("error in uploading image : \(error)")
}
else{
print("metadata in : \(metadata!)")
print(metadata?.downloadURL())
print("The pic has been uploaded")
print("download url : \(metadata?.downloadURL())")
self.uploadSuccess(metadata!, storagePath: filePath)
completionBlock()
}
})
})
}else{
print("No reference URL found!")
}
}
Downloading code : -
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
print("paths in user home page : \(paths)")
let documentDirectory = paths[0]
print("documents directory in homePage : \(documentDirectory)")
let filePath = "file:\(documentDirectory)/\(user!.uid).jpg"
var filePath2 : String = filePath
print(filePath)
let storagePath = NSUserDefaults.standardUserDefaults().objectForKey("storagePath") as! String
print("storagePath is : \(storagePath)")
storageRef.child("ProfilePictures").child(storagePath).writeToFile(NSURL.init(string: filePath)! , completion :
{ (url, err) -> Void in
if let error = err{
print("error while downloading your image :\(error)")
}else{
print("Download successful !")
print("the file filePath of the downloaded file : \(filePath)")
filePath2 = "\(documentDirectory)/\(self.user!.uid).jpg"
if let downloadedImage = UIImage(contentsOfFile: filePath2){
self.profilePictureImageView.image = downloadedImage
print("displayed")
}else{
print("unable to display")
}
}
})
where storagePath is something that you stored in your NSUserDefaults for later reference , such as this, while uploading your image to your firebase storage
The codeBlocks that i gave you are just one of many solutions, there are plenty of ways to do this, go to https://firebase.google.com/docs/storage/ios/download-files

Related

How to store videos in Firebase using Swift

I currently have a function that allows me to upload an image to Firebase Storage. But how in the world can I achieve the same, with a video instead of an image?
I suspect I have to change UIImage and .jpg to something else. But what is the type of a video?
#State var pickedImages: [UIImage] = []
#State var retrievedImages = [UIImage]()
This is my function:
func uploadImage() {
// Create storage reference
let storageRef = Storage.storage().reference()
// Turn our image into data
let selectedImage = pickedImages[0]
let imageData = selectedImage.jpegData(compressionQuality: 0.8)
guard imageData != nil else {
let er = "THIS: Error while converting to data"
return print(er)
}
// Specifie filepath and name
let path = "images/\(UUID().uuidString).jpg"
let fileRef = storageRef.child(path)
// Upload that data
let uploadTask = fileRef.putData(imageData!, metadata: nil) {metaData, error in
print("THIS: from uploadTAsk")
// Check for errors
if error == nil && metaData != nil {
// Save reference in firestore DB
let db = Firestore.firestore()
db.collection("images").document("user1").setData(["url": path]) { error in
print("THIS: inside closure")
// If there was no errors, display the image
if error == nil {
DispatchQueue.main.async {
self.retrievedImages.append(selectedImage)
}
}
}
}
}
}

Swift 4 Load 3D Models from Firebase

I'm trying to get a 3D Model which is stored in Firebase into my iOS Application.
Right now I stored the default Object (ship.scn) into my Firebase Storage.
How can I convert the Data, which I get from Firebase, to a SCNNode?
This is my Code right now:
let storage = Storage.storage().reference()
let modelPath = storage.child("models/ship.scn")
print("ModelPath: \(modelPath)")
modelPath.getMetadata { (metaData, error) in
if error != nil {
print("ERROR: ", error!)
}else{
print("Metadata: \(metaData!)")
}
}
// this is what firebase shows for images
// how can i get the Data as SCNNode?
modelPath.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if error != nil {
print("Error getData: \(error!)")
}else {
print(data)
}
}
I solved this problem by downloading the 3D Object from firebase into the devices document folder.
So when I need the 3D-object I create a reference to the downloaded 3D-Object
write To Directory: (where modelPath is the storage.child('your path') in firebase)
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let tempDirectory = URL.init(fileURLWithPath: paths, isDirectory: true)
let targetUrl = tempDirectory.appendingPathComponent("ship.scn")
modelPath.write(toFile: targetUrl) { (url, error) in
if error != nil {
print("ERROR: \(error!)")
}else{
print("modelPath.write OKAY")
}
}
load 3D file from directory:
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let tempDirectory = URL.init(fileURLWithPath: paths, isDirectory: true)
let targetUrl = tempDirectory.appendingPathComponent("\ship.scn")
var sceneForNode: SCNScene? = nil
do {
// load the 3D-Model node from directory path
sceneForNode = try SCNScene(url: targetUrl, options: nil)
}catch{
print(error)
}
// create node to display on scene
let node: SCNNode? = sceneForNode?.rootNode.childNode(withName: "ship", recursively: true)

Firebase Storage: the uploaded image doesn't saved on the app

I upload the image via .Camera to Firebase Storage. When I closed app and run again, this image don't saved at my app. I know that I missed something. Please, tell me what I should to add. Thank's a lot!
This is my code:
import UIKit
import Firebase
import FirebaseStorage
class PicturesOfCoinsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBAction func saveButton(_ sender: UIButton) {
saveOneEuroCentImage()
}
#IBOutlet weak var oneEuroCentImage: UIImageView!
#IBAction func usePhotoButton(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
picker.delegate = self
}
func saveOneEuroCentImage() {
let storageRef = FIRStorage.storage().reference().child("userPictures/oneEuroCent.jpg")
if let uploadData = UIImagePNGRepresentation(self.oneEuroCentImage.image!) {
storageRef.put(uploadData, metadata: nil) {(metadata, error) in
if error != nil {
print(error)
return
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
oneEuroCentImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
picker.dismiss(animated: true, completion: nil)
}
}
If you want to have a persistent copy of the image on your app then you must save the photo to your apps document directory before the upload. From your code above you are only uploading it to your cloud storage in firebase but there is no code for saving your picture locally, thats why it does not exist when the app is run again.
I suggest you create a documents directory file path or url for the image and then save it.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let path = paths.first
let imageFolderPath = path?.appending("MyFBImages")
if !FileManager.default.fileExists(atPath: imageFolderPath!){
do {
try FileManager.default.createDirectory(atPath: imageFolderPath!, withIntermediateDirectories: true, attributes: [:])
} catch let error {
print(error.localizedDescription)
}
}
let imageFilePath = imageFolderPath?.appending("myImageName.jpg")
let imageData = UIImageJPEGRepresentation(UIImage(), 1)
do {
try imageData?.write(to: URL(fileURLWithPath: imageFilePath!))
} catch let error {
print(error.localizedDescription)
}
N/B : the imageData in the code you can get that from the image you created just before the upload to firebase.
This should help you save your image locally. Next time you run your app you can access your previous images by initializing UIImage from contents of the url that holds your saved photos.
I hope this helps you out.

Swift 3: Image downloaded from Firebase and saved to local storage not showing in app

I am trying out a firebase storage function and I am unable to show the downloaded image in imageview. Download is successful but nothing shows. If I use a Image from assets it does show. Why is this not working?
DownloadViewController:
import UIKit
import FirebaseStorage
import Firebase
#objc(DownloadViewController)
class DownloadViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var statusTextView: UITextView!
var storageRef: FIRStorageReference!
override func viewDidLoad() {
super.viewDidLoad()
storageRef = FIRStorage.storage().reference()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = "file:\(documentsDirectory)/myimage.jpg"
let storagePath = UserDefaults.standard.object(forKey: "storagePath") as! String
// [START downloadimage]
storageRef.child(storagePath).write(toFile: URL.init(string: filePath)!,
completion: { (url, error) in
if let error = error {
print("Error downloading:\(error)")
self.statusTextView.text = "Download Failed"
return
}
self.statusTextView.text = "Download Succeeded!"
print("filepath: "+filePath)
let image = UIImage.init(contentsOfFile: filePath)
self.imageView.image = image
self.imageView.layoutIfNeeded()
self.imageView.clipsToBounds = true
})
// [END downloadimage]
}
}
Try adding .resume at the end of your function block like so:
}).resume
I assume the issue here is that your file doesn't exist:
let filePath = "file:\(documentsDirectory)/myimage.jpg"
Likely doesn't resolve to the correct user documents directory, and you should use something like (pardon the Obj-C, already answered this question with it):
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"hello"] URLByAppendingPathExtension:#"txt"];
This will also prevent issues of "works on the simulator but doesn't work on a device" and vice-versa.

Trouble uploading videos from iOS using WordPress REST api

I am very new at this, so sorry if I have missed something.
I am trying to upload a video from iOS to WordPress using the WP REST API and Alamofire.
Some videos will upload just fine while other videos get a rest_upload_no_content_disposition status = 400 error.
Here is my code to uploading a video
class func pageVideo(accessToken:String, filePath:NSURL, completion: AnyObject? -> Void) {
let endpoint = "http://XXXXXXXXX.com/wp-json/wp/v2/media/?access_token=\(accessToken)"
let parameters = [
"Content-Type": "multipart/form-data",
"Content-Disposition": "attachment; filename=appVideo.mov",
"media_type": "file"
]
var fileData : NSData?
if let fileContents = NSFileManager.defaultManager().contentsAtPath(filePath.path!) {
fileData = fileContents
}
let mgr = Alamofire.Manager.sharedInstance
mgr.upload(.POST, endpoint, multipartFormData: { multipartFormData in
if let _fileData = fileData {
multipartFormData.appendBodyPart(data: _fileData, name: "file", fileName: "file.mov", mimeType: "file/mov")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.response {(request, response, data, error ) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
if let dict = json as? NSDictionary{
if let url = dict.valueForKeyPath("source_url") as? String{
completion(url)
}
}
} catch let error as NSError{
// completion(error.localizedDescription)
print(error.localizedDescription)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
}
It seems like shorter videos work while anything over 30 seconds fails.
Even shorter videos that do upload take a very long time.
Any help would be greatly appreciated.
Nothing was wrong with my code I just needed to compress the videos. the longer videos were hitting the WordPress upload limit. Also it's always a good idea to compress videos or images that your uploading somewhere.

Resources