我尝试将照片上传到Firebase,但这给了我这个错误。它在Xcode 10之前可以正常工作。我收到此错误:
'UIImageJPEGRepresentation'已被实例方法'UIImage.jpegData(compressionQuality :)'代替
我不知道如何使用此功能。
import UIKit
import Firebase
class SignUpViewController:UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var tapToChangeProfileButton: UIButton!
var continueButton:RoundedWhiteButton!
var imagePicker:UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
continueButton.addTarget(self, action: #selector(handleSignUp), for:
.touchUpInside)
let imageTap = UITapGestureRecognizer(target: self, action:
#selector(openImagePicker))
profileImageView.isUserInteractionEnabled = true
profileImageView.addGestureRecognizer(imageTap)
profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
profileImageView.clipsToBounds = true
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
}
func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let storageRef = Storage.storage().reference().child("user/\(uid)")
guard let imageData = UIImageJPEGRepresentation(image, 0.75) else { return }
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
storageRef.putData(imageData, metadata: metaData) { metaData, error in
if error == nil, metaData != nil {
if let url = metaData?.downloadURL() {
completion(url)
} else {
completion(nil)
}
// success!
} else {
// failed
completion(nil)
}
}
}
}
答案 0 :(得分:84)
错误告诉您,从iOS 12开始,旧的UIImageJPEGRepresentation
函数已由UIImage
上的新jpegData
方法替换。
更改:
let imageData = UIImageJPEGRepresentation(image, 0.75)
收件人:
let imageData = image.jpegData(compressionQuality: 0.75)
类似地,UIImagePNGRepresentation
的使用已被pngData()
取代。
答案 1 :(得分:8)
只需更换
guard let imageData = UIImageJPEGRepresentation(image, 0.75) else { return }
具有:
guard let imageData = image.jpegData(compressionQuality: 0.75) else { return }
答案 2 :(得分:3)
此错误发生在ios 12和Swift 4.2版本中。
let image = UIImage()
let imageData = UIImageJPEGRepresentation(image, 1)
to:
let image = UIImage()
let imageData = image.jpegData(compressionQuality: 0.50)
您要这样更改。请尝试这个对我有用。