如何从UIImagePickerController获取图像的NSURL?上传到Firebase

时间:2016-06-25 16:59:52

标签: ios firebase uiimagepickercontroller nsurl firebase-storage

所以有一些其他线程开始,因为人们有这个问题。像这样:Obtain NSURL from UIImagePickerController和这一个: Firebase storage upload works in Simulator but not on iPhone

我正在尝试按照本教程: https://firebase.google.com/docs/storage/ios/upload-files#upload_from_a_local_file

我的视频上传工作,而不是图片。

我的视频代码很简单:

if mediaType.isEqualToString(kUTTypeMovie as String) {
        let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL

        fileToUploadURL = videoURL!
    }

但我的图片代码不起作用。这就是我最终得到的结果:

        let imageUrl = info["UIImagePickerControllerReferenceURL"] as? NSURL

        let assets = PHAsset.fetchAssetsWithALAssetURLs([imageUrl!], options: nil)
        let asset = assets.firstObject
        asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (contentEditingInput, info) in
            let imageFile = contentEditingInput?.fullSizeImageURL
            // now call putFile with imageFile instead of imageUrl
            self.fileToUploadURL = imageFile
        })

似乎无论我做什么我都会收到错误。 这是我当前的错误

2016-06-25 12:45:23.695 Chain[4187:1957121] Body file is unreachable: /var/mobile/Media/DCIM/100APPLE/IMG_0027.JPG
 Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0027.JPG”       couldn’t be opened because you don’t have permission to view it."

CONSOLE LOG

  

2016-06-25 12:47:59.108 Chain [4187:1957121]正文文件无法访问:/var/mobile/Media/DCIM/100APPLE/IMG_0027.JPG     错误域= NSCocoaErrorDomain代码= 257“无法打开文件”IMG_0027.JPG“,因为您无权查看它。” UserInfo = {NSURL = file:///var/mobile/Media/DCIM/100APPLE/IMG_0027.JPG,NSFilePath = / var / mobile / Media / DCIM / 100APPLE / IMG_0027.JPG,NSUnderlyingError = 0x18b7ad40 {Error Domain = NSPOSIXErrorDomain Code = 1“不允许操作”}}   2016-06-25 12:48:02.969 Chain [4187:1957659]插件com.swiftkey.SwiftKeyApp.Keyboard失效   可选([“public.image”,“public.movi​​e”])   info:[“UIImagePickerControllerOriginalImage”:size {1836,1454} orientation 0 scale 1.000000,“UIImagePickerControllerReferenceURL”:assets-library://asset/asset.JPG?id = 5FE3480C-0A3E-42B2-B83B-93D0F321A3B2& ext = JPG, “UIImagePickerControllerMediaType”:public.image,“UIImagePickerControllerCropRect”:NSRect:{{0,0},{1836,1452}},“UIImagePickerControllerEditedImage”:size {638,504} orientation 0 scale 1.000000]   fileToUploadURL:file:///var/mobile/Media/DCIM/100APPLE/IMG_0027.JPG   可选([“public.image”,“public.movi​​e”])   2016-06-25 13:01:58.845 Chain [4187:1958957]插件com.swiftkey.SwiftKeyApp.Keyboard失效   info:[“UIImagePickerControllerOriginalImage”:size {1836,1454} orientation 0 scale 1.000000,“UIImagePickerControllerReferenceURL”:assets-library://asset/asset.JPG?id = CFF5692E-2B93-407D-A9E4-48AC1BEDCAF2& ext = JPG, “UIImagePickerControllerMediaType”:public.image,“UIImagePickerControllerCropRect”:NSRect:{{0,0},{1836,1452}},“UIImagePickerControllerEditedImage”:size {638,504} orientation 0 scale 1.000000]   fileToUploadURL:nil

     

2016-06-25 13:04:05.136 Chain [4187:1957121] _BSMachError:(os / kern)无效的能力(20)   2016-06-25 13:04:05.138 Chain [4187:1959394] _BSMachError:(os / kern)无效的名字(15)   2016-06-25 13:04:05.146 Chain [4187:1959394] plugin com.swiftkey.SwiftKeyApp.Keyboard invalidated   2016-06-25 13:04:05.220 Chain [4187:1957188​​] CFNetwork SSLHandshake失败(-9806)   2016-06-25 13:04:05.661 Chain [4187:1957121]正文文件无法访问:/var/mobile/Media/DCIM/100APPLE/IMG_0015.JPG     错误域= NSCocoaErrorDomain代码= 257“无法打开文件”IMG_0015.JPG“,因为您无权查看它。” UserInfo = {NSURL = file:///var/mobile/Media/DCIM/100APPLE/IMG_0015.JPG,NSFilePath = / var / mobile / Media / DCIM / 100APPLE / IMG_0015.JPG,NSUnderlyingError = 0x18bd4330 {Error Domain = NSPOSIXErrorDomain Code = 1“不允许操作”}}

编辑:这是我的didFinishPickingMedia:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {


    let mediaType = info[UIImagePickerControllerMediaType] as! NSString

    print ("info: \(info)")

    if mediaType.isEqualToString(kUTTypeImage as String) {
        var newImage: UIImage

        if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
            newImage = possibleImage
        }
        else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
            newImage = possibleImage
        }

        else {
            return
        }

      /// CAN NOT GET NSURL working, NEED TO USE NSDATA
        if let jpegData:NSData = UIImageJPEGRepresentation(newImage, 80) {
            currentMediaTypeToUpload = "img"
            fileToUploadDATA = jpegData
        }

    }


    else if mediaType.isEqualToString(kUTTypeMovie as String) {
        let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL

        fileToUploadURL = videoURL!
        currentMediaTypeToUpload = "vid"
    }

3 个答案:

答案 0 :(得分:3)

解决方案在这里:how do I get NSURL for an image froom UIImagePickerController? for upload to Firebase

适用于我们的问题:

if  let referenceUrl = info[UIImagePickerControllerReferenceURL] {

        ////
        let assetURL = NSURL(string: String(referenceUrl))
        let assets = PHAsset.fetchAssetsWithALAssetURLs([assetURL!], options: nil)
        let asset: PHAsset = assets.firstObject as! PHAsset
        let manager = PHImageManager.defaultManager()
        let requestSize =   PHImageManagerMaximumSize
        manager.requestImageForAsset(asset, targetSize: requestSize, contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
            // Result is a UIImage
            // Either upload the UIImage directly or write it to a file
            let imageData = UIImageJPEGRepresentation(result!, 0.8)
            let imagePath = FIRAuth.auth()!.currentUser!.uid + "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000)).jpg"
            print ("filePath: ", imagePath)
            let metadata = FIRStorageMetadata()
            metadata.contentType = "image/jpeg"
            self.storageRef.child(imagePath)
                .putData(imageData!, metadata: metadata) { (metadata, error) in
                    if let error = error {
                        print("Error uploading: \(error.description)")
                        return
                    }
                    self.sendMessage([Constants.MessageFields.imageUrl: self.storageRef.child((metadata?.path)!).description])
                    print("Succeded")
            }

        })
    }

使用此解决方案,我可以将文件上传到firebase。

答案 1 :(得分:1)

NSURL返回的

UIImagePickerController具有方案assets-library://,该方案不能由文件系统URL库(包括我们的URL)直接访问。您必须通过Photos框架来检索内容,并将该数据写入单独的NSURL或将其上传到内存中。

  let assetURL = NSURL(string: "assets-library://path/to/content")
  let assets = PHAsset.fetchAssetsWithALAssetURLs([assetURL!], options: nil)
  let asset: PHAsset = assets.firstObject as! PHAsset

  let manager = PHImageManager.defaultManager()
  manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
    // Result is a UIImage
    // Either upload the UIImage directly or write it to a file
  })

此示例代码取自here,作为I / O对话Zero to App: Develop with Firebase的一部分。

答案 2 :(得分:0)

我不确定你是如何尝试从你的UIImagePickerController实例获取图像的,但是你可以实现委托并获取UIImage实例,然后使用'in-memory'方法将其上传到FirbaseStorage:< / p>

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
    guard let imageData = UIImageJPEGRepresentation(image, 1.0) else { return }

    let storageRef = FIRStorage.storage().referenceForURL("gs://project-id.appspot.com")
    imagesRef.putData(imageData, metadata: nil) { metadata, error in
        ...
    }
 }