iOS - Realm Query is not working properly - sql

I am using Swift(2.2) Realm Framework as doing with document. Here is my codes.
class SwipedAsset: Object{
dynamic var identifier = ""
dynamic var createdAt = ""
}
// save data
let realm = try! Realm()
let fileName = asset.originalFilename
if fileName != nil {
let swipedAssets = realm.objects(SwipedAsset.self).filter("identifier == '\(fileName!)'")
let assetCount = swipedAssets.count
if assetCount == 0 {
let swipedAsset = SwipedAsset()
if asset.originalFilename != nil {
swipedAsset.identifier = asset.originalFilename!
}
if asset.creationDate != nil {
let year = String(asset.creationDate!.year)[2...3]
let key = "\(asset.creationDate!.monthName) \(year)"
swipedAsset.createdAt = key
}
let realm = try! Realm()
try! realm.write{
realm.add(swipedAsset)
}
}
}
// load data
let realm = try! Realm()
let swipedAssets = realm.objects(SwipedAsset.self).filter("createdAt == '\(key)'")
let lastObject = swipedAssets.last
print(lastObject.identifier)
print(lastObject.createdAt)
Here, values are all "", "" Nothing, But swipedAssets.count = 3 I thought it means realm's query is working properly.
What's wrong with me ? Thanks for any help.

Please do not try to debug with breakpoint.

Related

Picture Storage as URL in SQLite DB in Swift 5

I have a swift project that uses an array of pictures. The array of pictures is kept in storage in the filmanager.default.urls path. The URLs are then kept in a SQLite database. I am able to add to the array without a problem, however, I run into an issue whenever I try to recall it from memory. I do not know if I am saving it wrong or loading it wrong. I will post the code for how I did that here.
func save(images: Array<UIImage>, identifier: String) -> Array<String> {
var picCounter = 0
var URLs: Array<String> = []
for pic in images {
let id = identifier + "makeSureThisCantAccidentallyBeAnID" + String(picCounter)
let jpgImageData = pic.jpegData(compressionQuality: 0.5)
let documentURL = fileManager.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first
let path = documentURL!.appendingPathComponent(id + ".png")
do {
try jpgImageData!.write(to: path)
} catch {
print(error)
}
picCounter += 1
URLs.append(path.absoluteString)
}
return URLs
}
That is my save function. It should store the URLs and return an array of URLs in string format.
Here is my loading function, it should take an array of URLs and return the array of images.
func recover(URLarray: Array<String>, identifier: String) -> Array<UIImage> {
if URLarray[0] == "fake url" {
let pic = #imageLiteral(resourceName: "LaunchScreen")
let fakeArray = [pic]
return fakeArray
}
var picCounter = 0
var imageArray: Array<UIImage> = []
for url in URLarray {
//let fileData = FileManager.default.contents(atPath: url)
guard let image = UIImage(contentsOfFile: url) else { return imageArray }
picCounter += 1
imageArray.append(image)
}
return imageArray
}
The "#imageliteral" is a literal image that is used instead of an array if there is no array to load. This should theoretically recall every image without returning nil. Lastly, I will post my SQLite saving function
func saveNote(note: Note) {
connect()
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(
database,
"UPDATE remember SET person = ?, memories = ?, imageurl = ? WHERE rowid = ?",
-1,
&statement,
nil
) == SQLITE_OK {
sqlite3_bind_text(statement, 1, NSString(string: note.person).utf8String, -1, nil)
sqlite3_bind_text(statement, 2, NSString(string: note.memories).utf8String, -1, nil)
var imageURL: String = ""
for url in note.imageURLs {
imageURL.append(url)
imageURL.append("#")
}
sqlite3_bind_text(statement, 3, NSString(string: imageURL).utf8String, -1, nil)
sqlite3_bind_int(statement, 4, note.id)
if sqlite3_step(statement) != SQLITE_DONE {
print("Error saving note")
}
}
else {
print("Error creating note update statement")
}
sqlite3_finalize(statement)
}
This is how I tried to save it. I had to store a URL array as one string so I decided to do so by making it a string I could split with the character "#" if you think that is the problem then please tell me what character or method I could use to do this, as I have tried changing the character. If anyone helps me this far then I am extremely grateful! Thank you!

Problemas with API Key

I'm having some difficulties trying to access the ontologias of AgroPortal, it says my api key is not valid but I created an account and it was given to me an api key.
I'm trying to do like I did with BioPortal since the API is the same but with the BioPortal it works, my code is like this:
function getAgroPortalOntologies() {
var searchString = "http://data.agroportal.lirmm.fr/ontologies?apikey=72574b5d-b741-42a4-b449-4c1b64dda19a&display_links=false&display_context=false";
// we cache results and try to retrieve them on every new execution.
var cache = CacheService.getPrivateCache();
var text;
if (cache.get("ontologies_fragments") == null) {
text = UrlFetchApp.fetch(searchString).getContentText();
splitResultAndCache(cache, "ontologies", text);
} else {
text = getCacheResultAndMerge(cache, "ontologies");
}
var doc = JSON.parse(text);
var ontologies = doc;
var ontologyDictionary = {};
for (ontologyIndex in doc) {
var ontology = doc[ontologyIndex];
ontologyDictionary[ontology.acronym] = {"name":ontology.name, "uri":ontology["#id"]};
}
return sortOnKeys(ontologyDictionary);
}
var result2 = UrlFetchApp.fetch("http://data.agroportal.lirmm.fr/annotator", options).getContentText();
And what I did with BioPortal is very similar, I did this:
function getBioPortalOntologies() {
var searchString = "http://data.bioontology.org/ontologies?apikey=df3b13de-1ff4-4396-a183-80cc845046cb&display_links=false&display_context=false";
// we cache results and try to retrieve them on every new execution.
var cache = CacheService.getPrivateCache();
var text;
if (cache.get("ontologies_fragments") == null) {
text = UrlFetchApp.fetch(searchString).getContentText();
splitResultAndCache(cache, "ontologies", text);
} else {
text = getCacheResultAndMerge(cache, "ontologies");
}
var doc = JSON.parse(text);
var ontologies = doc;
var ontologyDictionary = {};
for (ontologyIndex in doc) {
var ontology = doc[ontologyIndex];
ontologyDictionary[ontology.acronym] = {"name":ontology.name, "uri":ontology["#id"]};
}
return sortOnKeys(ontologyDictionary);
}
var result = UrlFetchApp.fetch("http://data.bioontology.org/annotator", options).getContentText();
Can someone help me?
Thanks, my regards.

Binary operator '-' cannot be applied to two (NSDate?) operators

Trying to get a total amount of time from a start time and end time.
I have the DateFormatter correct as in Extension.swift below but I am getting confused on the way to calculate bottomtime - starttime.
Any help is appreciated. Thanks
Extension.swift
extension NSDate{
var bottomtimestringValue: String{
return self.toString()
}
func tobottomtimeString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var bottomtimedateValue: NSDate?{
return self.toDate()
}
func tobottomtimeDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
Adddivelogviewcontroller.swift
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var sum = b - a
textFieldBottomTime.text = "\(sum)"
That's correct-- the - operator is not defined for NSDate?, so you can't find the difference that way. Since a and b are both NSDate?, you could find the difference like this:
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
Here, difference's type will be NSTimeInterval?.
Or if you prefer, you could add a definition of - for NSDate?, which might look like this:
func -(lhs:NSDate?, rhs:NSDate?) -> NSTimeInterval? {
if let left=lhs, right=rhs {
return left.timeIntervalSinceReferenceDate - right.timeIntervalSinceReferenceDate
} else {
return nil
}
}
Add that and you can use - above.
OK, not really sure if thats working or not but i get no errors. What I need this to do calculate after the end time picker OK botton is pressed
func OK3ButtonTapped(sender: UIBarButtonItem) {
self.textFieldEndTime.endEditing(true)
self.textFieldEndTime.text = endtimePickerView.date.endtimestringValue
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var difference: String = ""
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
textFieldBottomTime.text = "\(difference)"
}

'String' does not conform to protocol 'CollectionType' Error in Swift 2.0

I just downloaded XCode Beta 7 and received the error "Type 'String' does not conform to protocol 'CollectionType'". This is my first attempt at coding, so I'm not sure how to fix this. Thank you!!!
//the Pasteboard is nil if full access is not granted
let pbWrapped: UIPasteboard? = UIPasteboard.generalPasteboard()
if let pb = pbWrapped {
var type = UIPasteboardTypeListImage[0] as! String
if (count(type) > 0) && (image != nil) {
pb.setData(UIImagePNGRepresentation(image!)!, forPasteboardType: type)
var readDataWrapped: NSData? = pb.dataForPasteboardType(type)
if let readData = readDataWrapped {
var readImage = UIImage(data: readData, scale: 2)
print("\(image) == \(pb.image) == \(readImage)")
}
}
}
Change it to:
type.characters.count
Your code should then read:
//the Pasteboard is nil if full access is not granted
let pbWrapped: UIPasteboard? = UIPasteboard.generalPasteboard()
if let pb = pbWrapped {
var type = UIPasteboardTypeListImage[0] as! String
if (type.characters.count > 0) && (image != nil) {
pb.setData(UIImagePNGRepresentation(image!)!, forPasteboardType: type)
var readDataWrapped: NSData? = pb.dataForPasteboardType(type)
if let readData = readDataWrapped {
var readImage = UIImage(data: readData, scale: 2)
print("\(image) == \(pb.image) == \(readImage)")
}
}
}
Just a suggestion for where to start learning about this issue... https://developer.apple.com/swift/blog/?id=30
Strings in Swift 2

ActionScript 2.0 Random Boolean Function not working

I have the below code which show be randomly true and randomly false. But in my case its always being false. Any help is appreciated. Thanks.
In the below code tail and heads are the tow buttons.
on(release)
{
var guess:Boolean = Boolean(Math.round(Math.random()));
var input:Boolean;
if (event.target.name == "tail"){
input = true;
}
else if (event.target.name == "heads"){
input = false;
}
if (guess == input){
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
This will also work:
on(release)
{
var guess:Boolean = Boolean(Math.floor(Math.random()*2));
if (guess){
result.text = "Your Guess is corrent";
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
result.text = "Your Guess is wrong";
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
You dont need the event.target.name because the function is within the event handler of each button. So you can just use a random boolean. Event.target.name also doesnt work in AS2.0