我是swift 3(xcode)上的新人,我正在開發一個項目。我如何將挑選的圖像添加到核心數據
我正在構建一個包含核心數據的數據庫,並在其中插入數據。
現在在這個項目中,用戶可以在他的設備中選擇一張圖片,而不是將其保存到核心數據中。
我有這個至今:
func addUser() {
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
if (firstName.text == "" && lastName.text == "" && contact.text == "" && email.text == "") { //if we have a user profile delete it
deleteUser()
} else { //add a new user profile
newUser.setValue(firstName.text, forKey: "firstName")
newUser.setValue(lastName.text, forKey: "lastName")
newUser.setValue(contact.text, forKey: "contact")
newUser.setValue(email.text, forKey: "email")
let imgUrl = UIImagePickerControllerReferenceURL as! NSURL
print(imgUrl) //should print selected photo however not doing it
//Saving image
let img = UIImage(named: "imgUrl")
let imgData = UIImageJPEGRepresentation(img!, 1)
newUser.setValue(imgData, forKey: "photo")
print ("Data added in Users")
}
do {
try context.save()
} catch {
}
}
我讓用戶選擇帶的UIImagePickerController照片:
@IBAction func addPhoto(_ sender: UIButton) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
}
}
//image adding - galery
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
imageView.image = image
}
self.dismiss(animated: true, completion: nil)
}
現在缺少的東西,我知道。我如何讓用戶將他挑選的圖像保存到像這樣的核心數據中?
我應該得到選擇的圖像的網址嗎?我試過,但想不出:(還是有更好的解決辦法?
你應該__not__一個blob添加到直接任意數據庫(防止性能問題),也許你應該在一些地方保存二進制文件中的文件系統(例如無論是圖書館或文件夾)並在數據庫中只保留一個引用(例如文件名)。 – holex