问题
My swift code below is trying to to append the image that is in the pic image and save it into core data. The core data attributes are located in a image below. When the user enters 3 into the textfield the image the saved into core data should appear because that is the order in the index. 2 Images are saved when build so the new image should start at 3 on the index.
import UIKit
import CoreData
class ViewController: UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker: UIImagePickerController!
@IBOutlet var enterT : UITextField!
@IBOutlet var pic : UIImageView!
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
enterT.delegate = self
pic.backgroundColor = .cyan
populateData()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
// display an alert about invalid text
return true
}
loadImage(at: index - 1 )
return true
}
func loadImage(at index : Int) {
let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
fetchRequest.predicate = NSPredicate(format: "idx == %d", Int32(index))
do {
if let user = try context.fetch(fetchRequest).first {
pic.image = UIImage(data: user.image!)
} else {
pic.image = nil
}
} catch {
print("Could not fetch \(error) ")
}
}
@IBAction func add(){
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
@IBAction func append(){
}
func populateData()
{
let item = Users(context: context)
let vex = UIImage(named: "on.jpg")!.pngData()
item.image = vex
item.idx = 0
let item2 = Users(context: context)
let vex2 = UIImage(named: "house.jpg")!.pngData()
item2.image = vex2
item2.idx = 1
print("Storing Data..")
do {
try context.save()
} catch {
print("Storing data Failed", error)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
pic.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
}
回答1:
Look at the method populateData
, there is the code to create a record, to assign values to the attributes and to save the context.
If you want to add multiple images you have to calculate the next available index. The index is usually the number of saved items. If you have two predefined images at index 0
and 1
the next available index is 2
.
To get the number of saved records dynamically create a fetch request and call count(for:
on the context
let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
let nextAvailableIndex = try context.count(for: fetchRequest)
来源:https://stackoverflow.com/questions/60086549/save-image-to-binary-data-of-a-ordered-index