将UIImage视图转换为NSURL并将其上传到Firebase
我试图将图像从图像视图上传到Firebase存储。将UIImage视图转换为NSURL并将其上传到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。
你需要将图像转换为磁盘上的文件,并获得该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)
UIImageView上的.image属性保存对UIImage数据的引用。 let image = myImageView.image –
我会试着让你知道 – Mariah
对不起,UIImageJPEGRepresentation需要2个参数。我更新了答案。 –
首先确保您的硬盘上存在的图像,然后创建一个NSURL从它的路径。 – Roecrew