1

我是 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 一直告诉我“无法访问正文文件:/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 吗?

4

1 回答 1

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

您从中获取的 localFileinfo[UIImagePickerControllerReferenceURL] as! NSURL is不是图像 url,而是图像的资产库 URL。然后,您需要使用资产 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 然后具有设备上照片的绝对路径。

于 2016-05-30T06:41:12.513 回答