辛辛辛亦范辛挥方数 [英] Downloading image on Swift 2 form Firebase Storage

查看:129
本文介绍了辛辛辛亦范辛挥方数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我从Firebase存储中下载图像时,都会下载完美的图像,但是一旦我尝试将imageviewmy更改为图像视图,imageview就会消失。我没有约束,我导航到本地URL,并在那里找到完美的形象。任何帮助?我做错了什么?

  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) - >无效
if(error!= nil){
print(problem)
} else {
print(done)
}
}

downloadTask.observeStatus(.Success){(snapshot) - >无效
print(fileDestinationUrl)
var temp = String(fileDestinationUrl)
print(temp)
var my = UIImage(contentsOfFile:temp)
self.image。 image = my




$ b

解决方案

打印控制台中的destinationUrl,转到下载的文件位置,打开终端,将终端下载的图像拖放到终端上,终端会给出它的实际路径。终端给你的路径和控制台给你的路径,匹配那些。最喜欢他们是不同的,相应地改变他们。



示例代码: - $ / b>

上传代码: -
$ b $ pre $ func profilePictureUploading(infoOnThePicture:[String:AnyObject],completionBlock:(() - > Void)){

如果让referenceUrl = infoOnThePicture [UIImagePickerControllerReferenceURL] {
print(referenceUrl)
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as!NSURL],options:nil)
print资产)
let asset = assets.firstObject
print(资产)
资源?.requestContentEditingInputWithOptions(nil,completionHandler:{(ContentEditingInput,infoOfThePicture)in

let imageFile = ContentEditingInput?.fullSizeImageURL
print(imagefile:\(imageFile))

let filePath = FIRAuth.auth()!currentUser!.uid +/ \(Int (NSDate.timeIntervalSinceReferenceDate()* 1000))/ \(imageFile !)。
print(filePath:\(filePath))

FIRControllerClass.storageRef.child(ProfilePictures)。child(filePath).putFile(imageFile! ,元数据:无,完成:{(元数据,错误)在

如果错误!=无{

print(上传图片时出错:\(error) )



$ {b
$ b print(metadata in:\(metadata!))

打印(元数据?.downloadURL())

打印(图片已上传)

打印(下载url:\(metadata?.downloadURL() ))

self.uploadSuccess(metadata !, storagePath:filePath)

completionBlock()

}

})
))

} else {

print(No reference URL found!)

}



$ b

下载代码:

<$ p $
print(用户主页中的路径:\(路径))

让路径= NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
documentDirectory = path [0]
print(home目录下的documents目录:\(documentDirectory))

let filePath =file:\(documentDirectory)/ \(user! .uid).jpg
var filePath2:String = filePath
print(filePath)

let storagePath = NSUserDefaults.standardUserDefaults()。objectForKey(storagePath)as!字符串
print(storagePath is:\(storagePath))

storageRef.child(ProfilePictures)。child(storagePath).writeToFile(NSURL.init(string:filePath) !,完成:

{(url,err) - >无效

如果发生错误= err {

print(error while下载你的图片:\(error))


} else {

print(Download successful!)
print(the下载文件的文件filePath:\(filePath))
filePath2 =\(documentDirectory)/ \(self.user!.uid).jpg
if downloadImage = UIImage contentsOfFile:filePath2){
self.profilePictureImageView.image = downloadedImage
print(displayed)
} else {
print(无法显示)
}






$ b其中storagePath是存储在NSUse中的东西rDefaults供以后参考,比如这样,同时将你的图片上传到你的Firebase存储中。

我给你的codeBlock只是众多解决方案之一,有很多方法要执行此操作,请转至 https://firebase.google.com/docs/storage / ios /下载文件


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

这篇关于辛辛辛亦范辛挥方数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆