如何获取图像参考并将图像上传到Firebase?

时间:2016-05-30 02:05:23

标签: ios swift firebase firebase-storage

我是iOS开发的新手,我正在尝试使用Firebase存储服务来存储我的图片。我的应用程序中有以下方法,但我无法找到对UIImage的NSURL引用。我使用以下方法从库中获取图像。

@IBAction func getImage(sender: UIButton) {
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(image, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let theInfo: NSDictionary = info as NSDictionary
    let img: UIImage = theInfo.objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
    imageView.image = img

    let localFile = info[UIImagePickerControllerReferenceURL] as! NSURL
    uploadToFireBase(localFile)
    self.dismissViewControllerAnimated(true, completion: nil)
}

我使用此方法尝试将其上传到Firebase

func uploadToFireBase(localFile: NSURL) {
    let storageRef = FIRStorage.storage().referenceForURL("gs://logintest-90287.appspot.com/Pictures")
    let uploadTask = storageRef.putFile(localFile, metadata: nil) { metadata, error in
        if (error != nil) {
            // Uh-oh, an error occurred!
        } else {
            // Metadata contains file metadata such as size, content-type, and download URL.
            let downloadURL = metadata!.downloadURL
        }
    }
}

然而,XCode一直告诉我“Body文件无法访问:/asset.JPG”。我尝试使用以下方法获取NSURL,但它也不起作用。

    let imageUrl          = info[UIImagePickerControllerReferenceURL] as! NSURL
    let imageName         = imageUrl.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String!
    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
    let localPath         = photoURL.URLByAppendingPathComponent(imageName!)

有人可以帮忙告诉我如何将图片上传到Firebase吗?

1 个答案:

答案 0 :(得分:1)

let localFile = info[UIImagePickerControllerReferenceURL] as! NSURL
let assets = PHAsset.fetchAssetsWithALAssetURLs([localFile], options: nil)
let imageURL = assets.firstObject?.fullSizeImageURL
uploadToFireBase(imageURL)

您从info[UIImagePickerControllerReferenceURL] as! NSURL is获得的localFile不是图片网址,而是图片的素材资源库网址。然后,您需要使用资产URL获取资产,并将URL检索为完整大小的图像。

[[更新:1]]

我只能通过请求将照片作为可编辑对象来获得工作路径。不知道为什么。

let referenceUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (contentEditingInput, info) in
    let imageFile = contentEditingInput?.fullSizeImageURL
然后

imageFile具有设备上照片的绝对路径。