简体   繁体   English

我如何获取NSURL的图像清理UIImagePickerController? 上载到Firebase

[英]how do I get NSURL for an image froom UIImagePickerController? for upload to Firebase

So there have been a few other threads started because people have trouble with this. 因此,由于人们对此有麻烦,因此开始了其他一些线程。 like this one: Obtain NSURL from UIImagePickerController and this one: Firebase storage upload works in Simulator but not on iPhone 像这样一: 从UIImagePickerController获取NSURL,然后一: Firebase存储上载在Simulator中起作用,但在iPhone上不起作用

I am trying to follow this tutorial: https://firebase.google.com/docs/storage/ios/upload-files#upload_from_a_local_file 我正在尝试遵循本教程: https : //firebase.google.com/docs/storage/ios/upload-files#upload_from_a_local_file

My video uploads work, just not images. 我的视频可以上传,但不能上传图像。

My video code is straightforward: 我的视频代码很简单:

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

        fileToUploadURL = videoURL!
    }

but my image code doesn't work. 但是我的图片代码不起作用。 this is what i have ended up with: 这就是我最终得到的:

        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
        })

seems like no matter what I do I'm getting an error. 似乎无论我做什么我都会出错。 this is my current error 这是我目前的错误

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] 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." 2016-06-25 12:47:59.108链[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 "Operation not permitted"}} 2016-06-25 12:48:02.969 Chain[4187:1957659] plugin com.swiftkey.SwiftKeyApp.Keyboard invalidated Optional(["public.image", "public.movie"]) 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 Optional(["public.image", "public.movie"]) 2016-06-25 13:01:58.845 Chain[4187:1958957] plugin com.swiftkey.SwiftKeyApp.Keyboard invalidated info: ["UII 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使Optional([“ public.image”,“ public.movi​​e”]无效信息:[“ UIImagePickerControllerOriginalImage”:大小{1836,1454}方向0比例1.000000,“ UIImagePickerControllerReferenceURL”:asset-library://asset/asset.JPG?id = 5FE3480C-0A3E-42B2-B83B-93D0F321A3B2&ext = JPG,“ UIImagePickerControllerMediaType “:public.image,” UIImagePickerControllerCropRect“:NSRect:{{0,0},{1836,1452}},” UIImagePickerControllerEditedImage“:大小{638,504}方向0比例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。键盘无效的信息:[“ UII magePickerControllerOriginalImage": 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 magePickerControllerOriginalImage”:大小{1836,1454}方向0比例1.000000,“ UIImagePickerControllerReferenceURL”:assets-library://asset/asset.JPG?id = CFF5692E-2B93-407D-A9E4-48AC1BEDCAF2&ext = JPG,“ UIImagePickerControllerMediaType”:公开。图片,“ UIImagePickerControllerCropRect”:NSRect:{{0,0},{1836,1452}},“ UIImagePickerControllerEditedImage”:大小{638,504}方向0比例1.000000] fileToUploadURL:无

2016-06-25 13:04:05.136 Chain[4187:1957121] _BSMachError: (os/kern) invalid capability (20) 2016-06-25 13:04:05.138 Chain[4187:1959394] _BSMachError: (os/kern) invalid name (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 failed (-9806) 2016-06-25 13:04:05.661 Chain[4187:1957121] Body file is unreachable: /var/mobile/Media/DCIM/100APPLE/IMG_0015.JPG Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0015.JPG” couldn't be opened because you don't have permission to view it." 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]插件com.swiftkey.SwiftKeyApp.Keyboard无效2016-06-25 13:04:05.220 Chain [4187:1957188​​] CFNetwork SSLHandshake失败(-9806)2016-06-25 13:04:05.661链[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 "Operation not permitted"}} 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“不允许操作”}}

edit: this is my didFinishPickingMedia: 编辑:这是我的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"
    }

The solution is here: how do I get NSURL for an image froom UIImagePickerController? 解决方案在这里: 如何获取图像清理UIImagePickerController的NSURL? for upload to Firebase 上载到Firebase

Applied to our problem: 应用于我们的问题:

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")
            }

        })
    }

With this solution I could upload my files to firebase. 使用此解决方案,我可以将文件上传到Firebase。

NSURL s returned from UIImagePickerController s have the scheme assets-library:// , which isn't directly accessible by file system URL libs (ours included). UIImagePickerController返回的NSURL具有方案assets-library:// ,文件系统URL库(包括我们的库)不能直接访问该方案。 You'll have to go through the Photos framework to retrieve content, and either write that data to a separate NSURL or upload it in memory. 您将必须通过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
  })

This sample code taken from here , as part of our I/O talk Zero to App: Develop with Firebase . 此示例代码是从此处获取的 ,是我们I / O谈话“ 零应用程序:使用Firebase开发”的一部分

I'm not sure how exactly you're trying to get the image from your UIImagePickerController instance, but you can implement the delegate and get the UIImage instance and then upload it to FirbaseStorage using the 'in-memory' method: 我不确定您尝试从UIImagePickerController实例中获取图像的确切程度,但是您可以实现委托并获取UIImage实例,然后使用“内存中”方法将其上传到FirbaseStorage:

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
        ...
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取图像参考并将图像上传到 Firebase? - How do I get Image reference and upload image to Firebase? 如何在iOS的nsurl连接中使用Get方法将图像上传到服务器? - How to upload image to server with Get method in nsurl connection in ios? 如何使用UIImagePickerController相机图像更新UICollectionViewCell? - How do I use UIImagePickerController camera image to update my UICollectionViewCell? 你如何从 UIImagePickerController 获取图像文件名? - How do you get image file name from UIImagePickerController? 如何上传从UIImagePickerController中获取的图像 - How to upload image that was taken from UIImagePickerController 如何在uiimagepickercontroller中创建可裁剪的横幅图像? - How do I create a croppable banner image in uiimagepickercontroller? 如何将图像上传到Firebase存储并获取downloadURL的链接? - How do I upload images to Firebase Storage and get link for downloadURL? 如何通过 UIImagePickerController 或 QBImagePickerController 获取图片的 EXIF 数据? - How can I get the EXIF data of the image through UIImagePickerController or QBImagePickerController? 如何本地化UIImagePickerController - How do I localize UIImagePickerController iOS-如何将细分添加到NSURL? - IOS - How do I add segments to NSURL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM