Downloading image on Swift 2 form Firebase Storage

蹲街弑〆低调 提交于 2019-12-24 07:17:29

问题


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
        }


       }

回答1:


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



来源:https://stackoverflow.com/questions/37510771/downloading-image-on-swift-2-form-firebase-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!