我尝试将图片从图片视图上传到Firebase存储空间。
用户将从相册或相机到图像视图上传图像!我想要的是将此图像从图像视图上传到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。
答案 0 :(得分:3)
您需要将图片转换为磁盘上的文件并获取要上传的网址。
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)
答案 1 :(得分:0)
您可以获取所选图像的 PNG 字节并像这样上传,而不是将其转换为 NSURL:
storage.reference().child("images/imageName.png").putData(selectedImage!.pngData()!, metadata: nil, completion: {_, error in
guard error == nil else{
print("failed to upload image")
return
}
})