Set up Bar Code Scanner Database Through Parse Server: Swift - swift

I have a general question.
I have built in Xcode a unique QrCode that is generated based off of a user's objectID found in Parse Server.
Ultimately, I am trying to figure out how to scan that item using a scanner such as (another iphone, other mobile scanners) and once scanned, send that objectID and other information to that same parse database.
If that is not possible, I was wondering if it would be easier to scan it directly to Microsoft Excel and then manually input that data into parse (although this could take some time).
Here is my code:
import SwiftUI
import CoreImage.CIFilterBuiltins
let filter = CIFilter.qrCodeGenerator()
let context = CIContext()
var username = String()
var objectId = String()
//ViewDidLoad:
username = "Michael"
objectId = "Abc3432f5"
//qrCode Formatting
let image = generateQRCodeImage(string: objectId)
qrCodeImage.image = image
qrCodeImage.layer.magnificationFilter = CALayerContentsFilter(rawValue: kCISamplerFilterNearest)
//Functions
func generateQRCodeImage (string: String) -> UIImage {
let data = Data(string.utf8)
filter.setValue(data, forKey: "inputMessage")
if let qrCodeImage = filter.outputImage {
if let qrCodeCGImage = context.createCGImage(qrCodeImage, from: qrCodeImage.extent) {
return UIImage(cgImage: qrCodeCGImage)
}
}
return UIImage(systemName: "xmark") ?? UIImage()
}
And if so, is there a way to check if the data has already been uploaded to the excel spreadsheet?

Related

Get human readable name for Mac model on Ventura

I have used the following code for get the model identifier of a Mac computer:
public static var modelIdentifier: String {
var size = 0
sysctlbyname("hw.model", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: Int(size))
sysctlbyname("hw.model", &machine, &size, nil, 0)
return String(cString: machine)
}
This model identifier is used in this variable to get a human readable name of the device:
public static var marketingModel: String {
guard let currentIdentifier = NSLocale.current.languageCode else { return String.hyphen }
let modelIdentifier = self.modelIdentifier
var path = "/System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/"
path += currentIdentifier + ".lproj"
path += "/SIMachineAttributes.plist"
if let fileData = FileManager.default.contents(atPath: path) {
if let plistContents = try? PropertyListSerialization.propertyList(from: fileData, format: nil)
as? [String: Any]
{
if let contents = plistContents[modelIdentifier] as? [String: Any],
let localizable = contents["_LOCALIZABLE_"] as? [String: String]
{
let marketingModel = localizable["marketingModel"] ?? String.hyphen
return marketingModel
}
}
}
return String.hyphen
}
This returned strings like MacBook Pro (16-inch, 2019). However, on the latest MacOS Ventura build, no string is returned for Mac Mac Studio (Mac13,1).
Is there another way to get this string? Do I have to look in a different plist?
I have used the IORegistryExplorer and found a key that contains this information.
By running the following code in a playground, you can extract the name:
import Cocoa
import IOKit
let mainEntry = IORegistryEntryFromPath(kIOMainPortDefault, "IOService:/AppleARMPE/product")
let property = IORegistryEntryCreateCFProperty(mainEntry, "product-description" as CFString, kCFAllocatorDefault, 0)
if let bytes = property?.takeRetainedValue() as? Data
{
let array = [UInt8](bytes)
let terminatedModelString = String(cString: array)
Swift.print(terminatedModelString)
}
IOObjectRelease(mainEntry)
The key suggests that this will only work for Apple Silicon based machines. For Intel based machines, you can still use the code from my initial question.

Swift: Saving Multiple Images to Core Data

I have a Recipe entity with a one-to-many relationship to RecipeImage. The problem I'm having is how to properly save multiple images. What I'm trying to do is once I selected the images, I store them in a tempImageArray. Once I select "Done" I try to convert images within tempImageArray into an array of data since Core Data only accept images as Binary Data. I then set my recipe.images as that array of data.
Currently, I'm only able to save 1 photo instead multiple.
I think im close to the solution but just needs some guidance. Any help you be much appreciated!
class ListDetailViewController: UITableViewController {
var recipeToEdit: Recipe?
var recipeImages = [RecipeImage]()
//image collection
var tempImageArray = [UIImage]()
private func createRecipe() {
let context = CoreDataManager.shared.persistentContainer.viewContext
let recipe = NSEntityDescription.insertNewObject(forEntityName: "Recipe", into: context) as! Recipe
recipe.setValue(textField.text, forKey: "name")
let image = NSEntityDescription.insertNewObject(forEntityName: "RecipeImage", into: context) as! RecipeImage
for i in tempImageArray {
image.imageData = i.jpegData(compressionQuality: 0.8)
recipeImages.append(image)
}
recipe.images?.setValue(recipeImages, forKey: "images")
image.recipe = recipe
do {
try context.save()
//Perform save
navigationController?.popViewController(animated: true)
self.delegate?.didAddRecipe(recipe: recipe)
} catch let saveErr {
print("Failed to save recipe", saveErr)
}
}

how to store [UIImage] into Core Data and retrieve to [UIImage] from binary date

my code is like these:
//save to core data
func addPaper(){
let paper = Paper(context: self.context)
paper.id = UUID()
paper.subject = self.subject
paper.score = Float(self.score) ?? 0
paper.title = self.title
let imgs = try? NSKeyedArchiver.archivedData(withRootObject: self.images, requiringSecureCoding: true)
paper.images = imgs
try? self.context.save()
}
//retrieve to [UIImage]
let imgs = NSKeyedUnarchiver.unarchivedObject(ofClass: [UIImage], from: paper.images!)
there is an error tip:Static method 'unarchivedObject(ofClass:from:)' requires that '[UIImage]' conform to 'NSCoding'
I don't know what to do next, can anyone give me some help?
You should not store image in CoreData. Maybe store in base64 format, and you can encode/decode whenever you want.
Base64 To image:
func base64ToImage(data: String) -> Data{
let encodedImageData = data
let imageData = Data(base64Encoded: encodedImageData)
return imageData!
}
imageView.image = UIImage(data: dataDecoded)
Image to base64
func imageToBase64(image: UIImage) -> String {
return image.pngData()!
.base64EncodedString()
}
maybe you need this, any object can be saved to core data.
:https://stackoverflow.com/questions/56453857/how-to-save-existing-objects-to-core-data
I copied the following steps from others, hope it helps
1.making your custom types (Exercise) subclass of NSObject
2.setting the attribute's type in the core data model to Transformable
3.setting the CustomClass to [Exercise]

How to point a Json array to a local image?

I'm new at this so sorry if this is basic but I'm trying to use an array in a json file and have it point to an image in my asset library but I'm running into problems. Its written as:
[
{
"image":"shrew",
},
]
Is it wrong to write it as a string? Do I need to have specific code to translate the string into my image names?
Thanks for any help you can offer!
Edit:
The error I'm getting is on line
TrackPic.image = image
"Use of unresolved identifier 'TrackPic'"
class QuizModel: NSObject {
func getQuestions() -> [Question] {
// Array of question objects
var questions:[Question] = [Question]()
// Get Json array of dictionaries
let jsonObjects:[NSDictionary] = self.getLocalJsonFile()
// Loop through each dictionary and assign values to our question objs
var index:Int
for index = 0; index < jsonObjects.count; index++ {
// Current JSON dict
let jsonDictionary:NSDictionary = jsonObjects[index]
// Create a question obj
var q:Question = Question()
let imageName = jsonDictionary["image"] as! String
let image = UIImage(named: imageName)
TrackPic.image = image
// Assign the values of each key value pair to the question object
q.image = jsonDictionary["image"] as! String
q.questionText = jsonDictionary["question"] as! String
q.answers = jsonDictionary["answers"] as! [String]
q.correctAnswerIndex = jsonDictionary["correctIndex"] as! Int
q.module = jsonDictionary["module"] as! Int
q.lesson = jsonDictionary["lesson"] as! Int
q.feedback = jsonDictionary["feedback"] as! String
// Add the question to the question array
questions.append(q)
}
// Return list of question objects
return questions
}
you first need to get the image name from the json like you did
let imageName = jsonDictionary["image"] as! String
(If you want to be certain that you are parsing your JSON correctly, be sure to write the imageName to the console)
Then you need to initialise a UIImage with UIImage(named: String) with you image name from json so
let image = UIImage(named : imageName)
Then you have your image, and you can put this on an UIImageView.
I suppose in your case, this would be
q.image = image
IF q is a UIImageView

Swift - Populate core data from premade sqlite file

Not the same question as here.
I have a premade sqlite file that has three columns: chapter, verseNumber and verseText. My core data entity has the same name for its attributes. How do I populate the core data database from my sqlite file?
Core Data can not read arbitrary SQLite files. You would have to convert the file into a Core Data database manually. The format that Core Data uses to read from / write to SQLite is proprietary.
You have to use SQLite directly to read the data. I'd suggest using something like FMDB for reading the data. To put the data into a Core Data store, you should follow the guidelines of Efficiently Importing Data.
Here is what I ended up doing:
#IBAction func getSQLDB (sender: NSButton) {
let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let path = documentsFolder.stringByAppendingPathComponent("kjv.db")
println(documentsFolder)
let database = FMDatabase(path: path)
if !database.open() {
println("Unable to open database")
return
}
//if let rs = database.executeQuery("SELECT * FROM bible WHERE (book = 'Gen') AND (chapter = '1')", withArgumentsInArray: nil) {
if let rs = database.executeQuery("SELECT * FROM bible WHERE (book = 'Genesis') OR (book = 'Exodus')", withArgumentsInArray: nil) {
while rs.next() {
let content = rs.stringForColumn("content")
let verseNumber: Int! = rs.stringForColumn("verse").toInt()
let chapter: Int! = rs.stringForColumn("chapter").toInt()
let name = rs.stringForColumn("book")
// Loops through all the information from the query and creates a book
makeBook(name, content: content, chapter: chapter, verseNumber: verseNumber)
}
} else {
println("select failed: \(database.lastErrorMessage())")
}
database.close()
}