ios - 将 UIImage View 转换为 NSURL 以将其上传到 Firebase

标签 ios swift uiimage nsurl firebase-storage

我正在尝试将图像从 ImageView 上传到 Firebase 存储。

用户将从相册或相机上传图像到 ImageView !我想要的是将此图像从 ImageView 上传到 firebase 存储。

我尝试按照 Firebase 文档中的示例进行操作,如下所示:

   let localFile: NSURL = ImageView.image


    let metadata = FIRStorageMetadata()
    metadata.contentType = "image/jpeg"

    // Upload file and metadata to the object 'images/mountains.jpg'
    let uploadTask = storage.child("images/DeviceImage.jpg").putFile(localFile, metadata: metadata);

    // Listen for state changes, errors, and completion of the upload.
    uploadTask.observeStatus(.Pause) { snapshot in
        // Upload paused
    }

    uploadTask.observeStatus(.Resume) { snapshot in
        // Upload resumed, also fires when the upload starts
    }

    uploadTask.observeStatus(.Progress) { snapshot in
        // Upload reported progress
        if let progress = snapshot.progress {
            let percentComplete = 100.0 * Double(progress.completedUnitCount) / Double(progress.totalUnitCount)
        }
    }

    uploadTask.observeStatus(.Success) { snapshot in
        // Upload completed successfully
    }

    // Errors only occur in the "Failure" case
    uploadTask.observeStatus(.Failure) { snapshot in
        guard let storageError = snapshot.error else { return }
        guard let errorCode = FIRStorageErrorCode(rawValue: storageError.code) else { return }
        switch errorCode {
        case .ObjectNotFound:
            // File doesn't exist

        case .Unauthorized:
            // User doesn't have permission to access file

        case .Cancelled:
            // User canceled the upload

            ...

        case .Unknown:
            // Unknown error occurred, inspect the server response
        }
    }

但我不知道如何将 UIImageView 转换为 NSURL。

这是我得到的错误: enter image description here

最佳答案

您需要将图像转换为磁盘上的文件并获取要上传的 url。

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let filePath = "\(paths[0])/MyImageName.jpg"

// Save image.
UIImageJPEGRepresentation(image, 0.90)?.writeToFile(filePath, atomically: true)

参见:How do I save a UIImage to a file?

一旦写入磁盘,您就可以像这样获取文件的 url:

let localFile = NSURL(fileURLWithPath: filePath)

关于ios - 将 UIImage View 转换为 NSURL 以将其上传到 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39132898/

相关文章:

objective-c - 如何保存 UICollectionViewCell 的状态

swift - 如何等待异步任务结束 - Swift 4

ios - 如何在 Swift 中硬编码 UIView 的大小属性

ios - 为 iOS 设备构建成功但为 iOS 模拟器构建错误

ios - UIScrollView 滚动背景 View

ios - SwiftUI:如何知道修饰符的正确顺序?

ios - 从转换后的 UIImageView 裁剪 UIImage

iOS - 在本地保存图像的最佳实践 - NSCache 与保存在文档目录中

ios - 如何以编程方式将自定义图像设置为 UIBarButtonItem

ios - CAGradientLayer 搞砸了 CATransform3DRotate