I’m spending lots of time trying to figure this out and getting no where.
I have an entity with a NSDate attribute, which successfully saves.
How on Earth do I fetch the NSDate from the store(year only section) and make it populate the text on a button.
so the button can be pressed later and taken to another View Controller/Table View Controller.
I have spent hours trying to figure this out, I’m totally stuck can’t find any examples.
Does anyone have the time to help with this please.
Using Swift
(hopefully I have formated this question correctly, bit of a noob here)
Thank you for looking
//year button
#IBAction func btnYear(sender: AnyObject) {
//APP DEL REFERANCE
var appdel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appdel.managedObjectContext!
let ent = NSEntityDescription.entityForName("FilmInfo", inManagedObjectContext: context)!
// fetch request
var request = NSFetchRequest(entityName: "FilmInfo")
request.returnsObjectsAsFaults = false
First, get the date from your data.
object.date
Then, format it so you can display it on the button.
var formatter = NSDateFormatter()
formatter.dateStyle= .ShortStyle
let buttonTitle = formatter.stringFromDate(object.date)
Finally assign the title to the button
button.setTitle(buttonTitle, forState: .Normal)
To get to the object in the first place, fetch it. Don't forget to execute your fetch request.
var request = NSFetchRequest(entityName: "FilmInfo")
request.predicate = NSPredicate(format:"id = %#", aFilmInfoID) // example
request.fetchLimit = 1
let results = context.executeFetchRequest(request, error:nil)! as [FilmInfo]
let object = results.first!
You need to execute your fetch request in your context.
var resultsArray = context.executeFetchRequest(request,nil)
if let arr = resultsArray {
//we have some results
var firstObject: FilmInfo = arr[0] as FilmInfo
var date = firstObject.date
}
If you are interested in only one object you can always set request.fetchLimit = 1
Getting more advanced you can also fetch only the date property:
fetch.propertiesToFetch = ["date"]
fetch.resultType = .DictionaryResultType
Related
Any help would be great. Core Data is using "Date" for both due date and due time. Values are from Swift UI picker (displayedComponents: .date) and (displayedComponents: .hourAndMinute). It doesn't sort correctly.
var fetchCategories = [Category]()
let request: NSFetchRequest<Category> = Category.fetchRequest()
let predicate = NSPredicate(format: "isComplete == 0")
let sortDueDate = NSSortDescriptor(key: "dueDate", ascending: true)
let sortDueTime = NSSortDescriptor(key: "dueTime", ascending: false)
let sortDescriptors = [sortDueDate, sortDueTime]
request.sortDescriptors = sortDescriptors
request.predicate = predicate
do {
fetchCategories = try moc.fetch(request)
} catch {
print("Error fetching categories \(error.localizedDescription)")
}
return fetchCategories
A Date attribute in Core Data stores both date and time. I am guessing the dueTime attribute contains a date that is after the dueDate date, causing the sort issues.
The solution is to store the dueDate as just one attribute. This attribute contains both a date and a time, which you can modify separately in your user interface. You only need one SortDescriptor, too.
I can't seem to find any good documentation or tutorials that pertain to filtering core data in Swift 3.
I have the following code:
let tempVar: String = "abcdef"
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
/* Need code to modify the fetchRequest, so that it only pulls results where the "projectID" field is equal to whatever is stored in the tempVar variable. */
cstProjectDetails = try context.fetch(CSTProjectDetails.fetchRequest())
} catch {
print("There was an error fetching CST Project Details.")
}
Basically, I am just trying to do add a simple filter to the fetchRequest, so that it only pulls results from "cstProjectDetails" where the "projectID" field is equal to the contents of a previously set variable (in this case, "tempVar").
Any ideas?
Edit: The checked answer did the trick for me, but I had to make a quick adjustment to the code for the request initializer. Here is the code that I ended up with:
do {
let request: NSFetchRequest<CSTProjectDetails> = CSTProjectDetails.fetchRequest()
request.predicate = NSPredicate(format: "projectID == %#", cstProjectID)
cstProjectDetails = try context.fetch(request)
print(cstProjectDetails)
} catch {
print("There was an error fetching CST Project Details.")
}
You need a predicate attached to the request:
let request = CSTProjectDetails.fetchRequest()
request.predicate = NSPredicate(format: "projectID == %#", tempVar)
cstProjectDetails = try context.fetch(request)
Problem :
The process of loading images to Table View using their Paths that who stored in Core Data DB works fine , but the user experience not going well. The scroll is slow and buggy.
Importants Notes :
For my local DB i use Core Data
Im not saving the image it self in the Core Data , only their path(the image name)
As for the table view DataSource , i use an array of type Person that contains an ID and Img name(TableView rows equal array.Count).
-This is the url im getting my Json from (Check it out) - Json Link
All the object inside the Core Data DB
As far as i know , i did all the UI Updates in the Main theard
After each check im reloading the tableview.
This are the steps that being taking in a right sequence :
Get the data using NSURLSession - DataTask. After that "parsing" it and check if each object(In a for loop) exists in the Core Data DB,and than appending his variables to the TableView datasource array , and reloading the data
1)
let request = NSMutableURLRequest(URL: dataSourceURL!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
if data != nil {
let datasourceDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary
var DataArray = datasourceDictionary["descisions"] as NSArray
//Convert it to useable array
for var i = 0 ; i < DataArray.count ; i++ {
let ID_s = DataArray[i]["ID"]! as Int
//For each Object from the Json array i'm check if he is exisitng in the local DB
var ConvertetdID = Int32(ID_s)
let object : Lockdown? = self.CheckIfObjectExistInDBbyID(ConvertetdID)
//CheckIfExists - if it does , it return an object with the correct values
if object != nil {
//exists - load file from Core Data
let imgname = object!.imgPath
let photoRecord = PhotoRecord(name:"\(ConvertetdID)", url:imgname)
self.photos.append(photoRecord)
//TableView object array (photos)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
//After each check reload the tableView
}
}
}
}
task.resume()
Method that checks if he is exists or not in Core Data DB(the method receive the ID and returns object if exists and nil if not :
func CheckIfObjectExistInDBbyID(id : Int32) -> Lockdown? {
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
var request : NSFetchRequest = NSFetchRequest(entityName: "Lockdown")
request.predicate = NSPredicate(format: "id = %d", id)
var error : NSError?
request.fetchLimit = 1
var count : Int = managedContext.countForFetchRequest(request,error: &error)
if count == 0 {
// println("Error : \(error?.localizedDescription)")
println("Object \(id) Dosent exist in CoreData")
return nil
}
println("Object \(id) exist in CoreData")
let result = managedContext.executeFetchRequest(request, error: &error) as NSArray!
let lockdown = result.objectAtIndex(0) as Lockdown
println(lockdown.id)
return lockdown
}
cellForRowAtIndexPath method
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCelllet photoDetails = photos[indexPath.row]
cell.textLabel.text = photoDetails.name as String
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
var myPathList : NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var myPath = myPathList[0] as String
myPath = myPath.stringByAppendingPathComponent("\(photoDetails.name).png")
var image : UIImage = UIImage(contentsOfFile: myPath)!
dispatch_async(dispatch_get_main_queue()) {
cell.imageView.image = image
}
}
return cell
Any suggestions what is the cause of the problem?
You shouldn't always load the image from disk, it's slow. Instead, load the image from disk the first time and then store it in a cache (in memory). Check if the image is cached before loading it from disk.
You need to empty the cache if it gets too big or you get a memory warning.
Advanced versions can pre-cache some images for the cells that are just below the current scroll position.
You may be able to use a library for this, perhaps SDWebImage with file URLs (I haven't tried this).
The buggy part is because your async block doesn't check that the cell hasn't been reused before the image is loaded. If it has then the wrong image will appear on the reused cell (until it's replaced by another image). To fix, capture the indexPath in the block and get the cell for that indexPath once the image is loaded - if the table view returns nil then the cell is no longer visible and you don't need to do anything other than cache the image for future use.
I have a notes form with a rich text field on it, called "Body". I've set the "Storage" property of the field to "Store contents as HTML and MIME".
Now, I am creating a new document with that form in the Notes Client.
However, if I try to access the rich text field's value in SSJS with NotesRichTextItem.getMIMEEntity(), it always returns null.
Am I missing something?
Thank you for your help in advance.
Update 2: 02/12/2015
I did some more testing and I found the cause, why it won't recognize the rich text field as MIME Type, but rather always returns it as RICH TEXT:
The cause is me accessing the database with "sessionAsSigner" rather than just using "database".
If I remove "sessionAsSigner" and use "database" instead, making the XPage unavailable to public access users, so, I am forced to log in, the code recognizes it as MIME Type and I can get a handle on NotesMIMEEntity.
Unfortunately, the XPage has to be available to public access users and I have to use sessionAsSigner.
When I open the document properties and I look at the rich text field, I can see that the "Field Flags" are "SIGN SEAL". My guess is, that's why sessionAsSigner doesn't work, but it is just a guess.
Any ideas?
Update 1: 02/12/2015
Here is the code I am using in my SSJS:
var oDBCurrent:NotesDatabase = sessionAsSigner.getDatabase(session.getServerName(), session.getCurrentDatabase().getFilePath());
var oVWMailProfiles:NotesView = oDBCurrent.getView('$vwSYSLookupEmailProfiles');
var oVWPWResetRecipient:NotesView = oDBCurrent.getView('$vwPWPMLookupPWResetNotificationProfiles');
var oDocPWResetRecipient:NotesDocument = null;
var oDocMailProfile:NotesDocument = null;
var oDocMail:NotesDocument = null;
var sServer = session.getServerName();
oDocPWResetRecipient = oVWPWResetRecipient.getDocumentByKey(sServer, true);
oDocMailProfile = oVWMailProfiles.getDocumentByKey('.MailTemplate', true);
oDocMail = oDBCurrent.createDocument();
//Set default fields
oDocMail.replaceItemValue('Form', 'Memo');
oDocMail.replaceItemValue('Subject', oDocMailProfile.getItemValueString('iTxtSubject'));
oDocMail.replaceItemValue('SendTo', oDocPWResetRecipient.getItemValue('iNmesRecipients'))
//Get body text
var oItem:NotesItem = oDocMailProfile.getFirstItem("Body");
var entity:NotesMIMEEntity = oItem.getMIMEEntity();
//Create email body
var tmp = entity.getContentAsText();
//Replace <part2> with part 2 of the password
tmp = #ReplaceSubstring(tmp, "<part2>", sPWPart2);
//Set content of Body field as MIME type
var body = oDocMail.createMIMEEntity();
var stream = session.createStream();
stream.writeText(tmp);
body.setContentFromText(stream, "text/html; charset=iso-8859-1", 0);
//Send email
oDocMail.send();
As I mentioned before, I've also tried:
var oDBCurrent:NotesDatabase = sessionAsSigner.getDatabase(session.getServerName(), session.getCurrentDatabase().getFilePath());
var oVWMailProfiles:NotesView = oDBCurrent.getView('$vwSYSLookupEmailProfiles');
var oVWPWResetRecipient:NotesView = oDBCurrent.getView('$vwPWPMLookupPWResetNotificationProfiles');
var oDocPWResetRecipient:NotesDocument = null;
var oDocMailProfile:NotesDocument = null;
var oDocMail:NotesDocument = null;
var sServer = session.getServerName();
oDocPWResetRecipient = oVWPWResetRecipient.getDocumentByKey(sServer, true);
oDocMailProfile = oVWMailProfiles.getDocumentByKey('.MailTemplate', true);
oDocMail = oDBCurrent.createDocument();
//Set default fields
oDocMail.replaceItemValue('Form', 'Memo');
oDocMail.replaceItemValue('Subject', oDocMailProfile.getItemValueString('iTxtSubject'));
oDocMail.replaceItemValue('SendTo', oDocPWResetRecipient.getItemValue('iNmesRecipients'))
//Get body text
var entity:NotesMIMEEntity = oDocMailProfile.getMIMEEntity('Body');
//Create email body
var tmp = entity.getContentAsText();
//Replace <part2> with part 2 of the password
tmp = #ReplaceSubstring(tmp, "<part2>", sPWPart2);
//Set content of Body field as MIME type
var body = oDocMail.createMIMEEntity();
var stream = session.createStream();
stream.writeText(tmp);
body.setContentFromText(stream, "text/html; charset=iso-8859-1", 0);
//Send email
oDocMail.send();
Try calling sessionAsSigner.setConvertMime(false)
You get the MIMEEntity from the document, not from the Richtext item. See an example here (starting at line 103): https://github.com/zeromancer1972/OSnippets/blob/master/CustomControls/ccSnippets.xsp
You should set the session to not convert MIME to RichText.
Add this at the start of your code.
session.setConvertMime(false);
I would like to set the string value to the object id when I create the object below. At the moment it prints "nil". Any ideas? Thanks
var date:NSDate = currentDatePicker.date
var DOB:NSDate = DOBPicker.date
var user = PFUser.currentUser()
var report = PFObject(className:"reports")
report["name"] = nameTextField.text
report["DOB"] = DOB
report["date"] = date
report["user"] = user
report.saveInBackground()
var ojId = report.objectId
println(ojId)
saveInBackground is an asynchronous method, so it doesn't wait. The reason why the id is not set is because the entity has not been saved yet.
I think you should use saveInBackgroundWithBlock: and retrieve the object id form within the block (which is executed after the entity has been saved):
var report = PFObject(className:"reports")
report["name"] = nameTextField.text
report["DOB"] = DOB
report["date"] = date
report["user"] = user
report.saveInBackgroundWithBlock { (success, error) -> Void in
if success {
var ojId = report.objectId
println(ojId)
}
}
or maybe also save, which is performed synchronously - but do not use that from the main thread:
report.save()
var ojId = report.objectId
println(ojId)