1

私は iOS 開発が初めてで、Firebase Storage サービスを使用して画像を保存しようとしています。アプリに次のメソッドがありますが、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 に答える