为什么Xcode会向我抱怨关于上传图像到Firebase存储的权限,但当我在模拟器中运行相同的应用程序时,它工作得很好呢?
权限错误:
正文文件无法访问:/var/mobile/media/dcim/100apple/img_0974.jpg Error domain=nscocoaerrordomain code=257“无法打开img_0974.jpg文件,因为您没有查看该文件得权限。”UserInfo=nsurl=file:///var/mobile/media/dcim/100apple/img_0974.jpg,nsFilePath=/var/mobile/media/dcim/100apple/img_0974.jpg,nsUnderlyingError=0x14805D680 Error Domain=nsposixErrordomain Code=1“不允许操作}
我现在也有同样的问题。在模拟器中上传工作良好,但在设备上它给我权限错误。我的解决办法是将图像作为数据上传,而不是将URL上传到文件:
let imageData = UIImageJPEGRepresentation(image, 1.0)
let uploadTask = storageReference.child(remoteFilePath).putData(imageData, metadata: metadata, completion: { (metadata, error) in
// Your code here
}
在模拟器中上传工作良好,但在设备上它给我权限错误。将图像作为数据上载,而不是与URL一起上载到文件:
先申报
fileprivate lazy var storageRef: StorageReference = Storage.storage().reference(forURL: "gs://yourAPP.appspot.com/")
然后
let path : String = "\(String(describing: Auth.auth().currentUser?.uid))/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\(photoReference)"
// 6
let imageData = UIImageJPEGRepresentation(photoReference, 0.1)
let uploadTask = self.storageRef.child(path).putData(imageData!, metadata: nil, completion: { (metadata, error) in
// Your code here
if let error = error {
print("Error uploading photo: \(error.localizedDescription)")
return
}
// 7
self.setImageURL(self.storageRef.child((metadata?.path)!).description, forPhotoMessageWithKey: key)
})
谢谢你和所有回答问题的人。。。我试过这个。。。下面的代码位于DidFinishPickingMediaWithInfo..中。我评论了当用户从照片库中选取图像时处理的代码,并且再次感谢您,所以我的代码是(下面)
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
picker.dismissViewControllerAnimated(true,completion:nil)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage//<--
let imageData = UIImageJPEGRepresentation(image, 1.0)
let imagePath = "photos/xxxyyyzzz.jpg"//whatever you want
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
storageRef.child(imagePath).putData(imageData!,metadata:metadata){
(metadata, error) in
if let error = error{
print("Error uploading photo: \(error)")
}
else{
//if there is no error the compiler will come here
print("no error")
//and maybe you want to use the full url or download url after success
//for example you wanna have tha downloadURL...
let downloadURL = metadata!.downloadURL()
print("\(downloadURL)")
//do whatever you want...
}
}
}