Parse LiveQuery How do I uses Loadmore , limits - swift

Hi I'm uses ParseLiveQuery and PFSubclassing in Swift 3
My question is limits is not working for me.
Here is my PFSubclassing
import Foundation
import Parse
class Post: PFObject, PFSubclassing {
#NSManaged var postBy: PFUser?
#NSManaged var postText: String?
#NSManaged var postImg: PFFile?
#NSManaged var sell: NSNumber?
#NSManaged var commentPointer: PFObject?
#NSManaged var commentBy: PFUser?
#NSManaged var comment: String?
#NSManaged var likeCount: NSNumber?
#NSManaged var mention: NSArray?
#NSManaged var hashtag: NSArray?
static func parseClassName() -> String {
return "Post"
}
override class func query() -> PFQuery<PFObject>? {
let query = PFQuery(className: Post.parseClassName())
query.whereKeyExists("objectId")
query.includeKeys(["postBy", "commentPointer", "commentPointer.commentBy", "commentBy"])
query.order(byDescending: "createdAt")
query.cachePolicy = .networkElseCache
return query
}
}
And It is my tableVieController
class FeedVC: UITableViewController, ShopDetailDelegate {
private var subscription: Subscription<Post>!
//Add friends and me
var postLiveQuery: PFQuery<Post> {
return Post.query() as! PFQuery<Post>
}
var client: Client {
return ParseLiveQuery.Client.shared
}
var results = [Post]()
I had declare subscription in ViewDidLoad()
subscription = client.subscribe(postLiveQuery).handleSubscribe { [weak self] (_) in
// Fetch the objects on subscription to not miss any
self?.fetchObjects()
}.handleEvent { [weak self] (_, event) in
self?.handleEvent(event: event)
}
And Here is what I'm trying to this.
func fetchObjects() {
postLiveQuery.limit = self.page
postLiveQuery.findObjectsInBackground().continue(with: BFExecutor.mainThread(), with: { (task) -> Any? in
guard let objects = task.result as? [Post] else {
return nil
}
self.results = objects
self.tableView.reloadData()
print("Got it!!!")
print(objects)
return nil
})
}
//load more
func morefetchObjects() {
if page <= results.count {
//Start animating indicator
indicator.startAnimating()
//increase page size to load + 10 posts
page = page + 1
postLiveQuery.limit = self.page
postLiveQuery.findObjectsInBackground().continue(with: BFExecutor.mainThread(), with: { (task) -> Any? in
guard let objects = task.result as? [Post] else {
return nil
}
self.results = objects
self.tableView.reloadData()
print("morefetchObjects")
print(objects)
return nil
})
}
}
//scrolled down
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= scrollView.contentSize.height - self.view.frame.size.height * 2 {
morefetchObjects()
}
}
It works fine but When I called fetchObject() then It retrieve all of datas from parse-server. I want fetch only limits and then When I scroll down I wish to get retrieve more data.
How can I implement this?

Related

How to load data in the collectionview from JSON to Swift by using Alamofire and Kingfisher

I need to get the data from already made JSON file to the Swift. By using MVVM desing I wrote this code in the Repo class
func loadFoods() {
AF.request("http://example.com/foods/getAllFoods.php",method: .get).response { response in
if let data = response.data {
do{
let result = try JSONDecoder().decode(ProductsResponse.self, from: data)
if let list = result.foods {
self.foodList.onNext(list)
}
}catch{
print(error.localizedDescription)
}
}
}
}
Here's the code from View Model class:
class HomeViewModel {
var foodList = BehaviorSubject <[Foods]>(value: [Foods]())
var frepo = FoodsDaoRepository()
init() {
loadFoods()
foodList = frepo.foodList
}
func loadFoods() {
frepo.loadFoods()
}
func loadPersons(){
prepo.loadPersons()
}
and I wrote this code in the ViewContoller class:
override func viewDidLoad() {
super.viewDidLoad()
searchTextField.delegate = self
collectionView.delegate = self
collectionView.dataSource = self
let _ = viewModel.foodList.subscribe(onNext: { list in
self.foodsList = list
DispatchQueue.main.async {
self.collectionView.reloadData()
}
})
override func viewWillAppear(_ animated: Bool) {
viewModel.loadFoods()
}
Foodlist variable takes the data from Food class:
class Foods: Codable {
var id : Int?
var name : String?
var image : String?
var price : Int?
var category : String?
init(id: Int?, name: String?, image: String?, price: Int?, category: String?) {
self.id = id
self.name = name
self.image = image
self.price = price
self.category = category
}
}
But it didn't help to get the data from JSON to the CollectionView. It just shows empty collection view cells.
Also how can I get an image by using Kingfisher and Alamofire?
I tried to explain the problem and wrote a code to expand my question

Loading data from Parse server into a model file in an array.

I want to load data from parse server into a model file in an array called posts but i don't know how.
Here is the code :
struct Post
{
var createdBy: User
var timeAgo: String?
var caption: String?
var image: UIImage?
var numberOfLikes: Int?
var numberOfComments: Int?
var numberOfShares: Int?
static func fetchPosts() -> [Post]
{
var posts = [Post]()
var usernameArray = [String]()
var avaArray = [PFFile]()
var dateArray = [Date?]()
var picArray = [PFFile]()
var titleArray = [String]()
var uuidArray = [String]()
let query = PFQuery(className: "posts")
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if error == nil {
usernameArray.removeAll(keepingCapacity: false)
avaArray.removeAll(keepingCapacity: false)
dateArray.removeAll(keepingCapacity: false)
picArray.removeAll(keepingCapacity: false)
titleArray.removeAll(keepingCapacity: false)
uuidArray.removeAll(keepingCapacity: false)
// find related objects
for object in objects! {
usernameArray.append(object.object(forKey: "username") as! String)
avaArray.append(object.object(forKey: "ava") as! PFFile)
dateArray.append(object.createdAt)
picArray.append(object.object(forKey: "pic") as! PFFile)
titleArray.append(object.object(forKey: "title") as! String)
uuidArray.append(object.object(forKey: "uuid") as! String)
}
}
}
return posts
}
}
struct User
{
var username: String?
var profileImage: UIImage?
}
Try this
static func fetchPosts() -> [Post]
{
var posts = [Post]()
var usernameArray = [String]()
var avaArray = [PFFile]()
var dateArray = [Date?]()
var picArray = [PFFile]()
var titleArray = [String]()
var uuidArray = [String]()
let query = PFQuery(className: "posts")
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if error == nil {
// find related objects
if let returnedObjects = objects {
for object in returnedObjects {
usernameArray.append(object["username"] as! String)
avaArray.append(object["ava"] as! PFFile)
dateArray.append(object.createdAt)
picArray.append(object["pic" as! PFFile)
titleArray.append(object["title"] as! String)
uuidArray.append(object["uuid"] as! String)
}
}
}
}
return posts
}
In order to append data to your posts you need to
- Convert PFFile to UIImage
- Create a User object with the UIImage
- Add the User object to your posts
if let avaPicture = object["ava"]! as! PFFile {
avaPicture.getDataInBackground({ (imageData: Data?, error: Error?) -> Void in
if (error == nil) {
let image = UIImage(data: imageData!)
if image != nil {
// Create your User object with UIImage here
let user = User()...
// Add the new user and other data to your `posts`array
...
}
}
})
}

How do I update tableview cell when It had changed

When I scroll up&down then tableview cell has set overtimes so It affect lagging.
I want to update only when the data is updated.
Post.swift (It is model)
import Foundation
import Parse
class Post: PFObject, PFSubclassing {
#NSManaged var postBy: PFUser?
#NSManaged var postUser: String?
#NSManaged var postUserImg: PFFile?
#NSManaged var postText: String?
#NSManaged var postImg: PFFile?
#NSManaged var sell: NSNumber?
#NSManaged var commentPointer: PFObject?
#NSManaged var commentBy: String?
#NSManaged var comment: String?
#NSManaged var liked: NSArray?
#NSManaged var likeCount: NSNumber?
#NSManaged var mention: NSArray?
#NSManaged var hashtag: NSArray?
static func parseClassName() -> String {
return "Post"
}
override class func query() -> PFQuery<PFObject>? {
let query = PFQuery(className: Post.parseClassName())
return query
}
}
extension Post: FeedCellSupport {
var username:String?{
return postUser
}
var userImg:PFFile?{
return postUserImg
}
var commentText:String?{
guard let commentTxt = comment else {
return ""
}
return commentTxt
}
TableView.swift
protocol FeedCellSupport {
var postDate: String? { get }
var postId: String? { get }
var postObj: PFObject? { get }
var img: PFFile? { get }
var username:String?{ get }
var userImg:PFFile?{ get }
var commentText:String?{ get }
var commentFrom:String?{ get }
var postText: String? { get }
var likes: Int? { get }
var isLiked: Bool? { get }
var isSell: Bool? { get }
var hashtags: NSArray? { get }
var mentions: NSArray? { get }
}
func fetchObjects() {
let postQuery = Post.query()?
.whereKeyExists("objectId")
.includeKeys(["postBy", "commentPointer", "commentPointer.commentBy", "commentBy"])
.order(byDescending: "createdAt")
as! PFQuery<Post>
postQuery.limit = self.page
postQuery.cachePolicy = .networkElseCache
postQuery.findObjectsInBackground { (object:[Post]?, error:Error?) in
if error == nil {
self.results = object!
}else {
print(error?.localizedDescription as Any)
}
self.tableView.reloadData()
self.refresher.endRefreshing()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ShopDetailCell", for: indexPath) as! ShopDetailCell
if let object = results[indexPath.row] as? FeedCellSupport{
cell.postID = object.postObj!
cell.userNameLabel.text = object.username!
cell.userNameLabel.sizeToFit()
cell.descriptionLabel.text = object.postText!
cell.descriptionLabel.sizeToFit()
cell.commentByLabel.text = object.commentFrom!
cell.commentByLabel.sizeToFit()
cell.commentLabel.text = object.commentText!
cell.commentLabel.sizeToFit()
cell.delegate = self
}
return cell
}
How can I ensure that data is updated only when it changes?
What are your App functionalities? Your problem is associated with the way suitable to accomplish your task, that is: to update app contents.
So it is about business logic: when should the information be updated?
The solution to your problem is using user toggled events to refresh the contents or other possible solutions such as Application Delegate.
Except for these answers, the contents cannot update tableview automatically as your expectation.
Update
I considered this line of code is lagging:
if let object = results[indexPath.row] as? FeedCellSupport{
//other code
}
Because code inside these braces is dealing with data setting. You could try to mock up local data instead of this results array to say whether this is the problem.

Retrieving image from firebase? (swift)

So i have a firebase structure like the pic below
Now i want to retrieve that image file that i've uploaded. to decode the base64String and show it. Every user can make a post and the information that will be sended to firebase has a description etc. and also have an image. now i tried to retrieve it whit this codes but nothing did work.
var REF_LIST = Firebase(url: "\(URL_BASE)/listItems")
REF_LIST.observeEventType(FEventType.Value, withBlock: { snapshot in
let image = snapshot.value.objectForKey("images") as! String
but this already gave me a nil error on that line, so i couldn't even decode. i think i understand why it's giving me a nil error, there is no images in listItems on firebase, you first have the unique ID and then the specs with images in. now i don't now how i can retrieve that information from that unique ID?
UPDATE:
the tableViewController what will receive the data from firebase:
import UIKit
import FBSDKLoginKit
import Alamofire
import Firebase
class ListVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var lists = [List]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
dispatch_async(backgroundQueue, {
self.initObservers()
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
func initObservers() {
LoadingOverlay.shared.showOverlay(self.view)
DataService.ds.REF_LISTS.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.lists = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
print("SNAP: \(snap)")
if let listDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let list = List(listKey: key, dictionary: listDict)
self.lists.insert(list, atIndex:0)
}
}
}
self.tableView.reloadData()
LoadingOverlay.shared.hideOverlayView()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as? ListCell {
let list = self.lists[indexPath.row]
cell.request?.cancel()
cell.configureCell(list)
return cell
} else {
return ListCell()
}
}
}
the addController which post the data to firebase:
import UIKit
import Firebase
import Alamofire
import FBSDKCoreKit
class AddVC: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var addTitle: UITextField!
#IBOutlet weak var addDescription: UITextView!
#IBOutlet weak var addLocation: UITextField!
#IBOutlet weak var placeholderLbl: UILabel!
#IBOutlet weak var freeSwitch: UISwitch!
#IBOutlet weak var tradeSwitch: UISwitch!
#IBOutlet weak var imageSelectorImg: UIImageView!
#IBOutlet weak var overlayView: UIView!
var currentUsername = ""
var imageSelected = false
var imagePicker: UIImagePickerController!
var base64String: NSString = ""
override func viewDidLoad() {
super.viewDidLoad()
addTitle.delegate = self
addDescription.delegate = self
addLocation.delegate = self
imagePicker = UIImagePickerController()
imagePicker.delegate = self
getCurrentUser()
hideKeyboardWhenTappedAround()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
addTitle.text = ""
addDescription.text = ""
addLocation.text = ""
freeSwitch.setOn(false, animated: false)
tradeSwitch.setOn(false, animated: false)
placeholderLbl.hidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getCurrentUser() {
DataService.ds.REF_USER_CURRENT.observeEventType(FEventType.Value, withBlock: { snapshot in
let currentUser = snapshot.value.objectForKey("username") as! String
print("Username: \(currentUser)")
self.currentUsername = currentUser }, withCancelBlock: { error in
print(error.description)
})
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImg.image = image
dispatch_async(backgroundQueue, {
let uploadImage = image
let imageData = UIImageJPEGRepresentation(uploadImage, 0.5)
self.base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
})
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
func postToFirebase() {
// LoadingOverlay.shared.showOverlay(self.overlayView)
var post: Dictionary<String, AnyObject> = ["username": self.currentUsername, "description": self.addDescription.text!, "title": self.addTitle.text!, "location": self.addLocation.text!, "images": self.base64String]
if self.freeSwitch.on && self.tradeSwitch.on {
post["tradeOption"] = "Gratis/Te ruil"
} else if self.freeSwitch.on {
post["tradeOption"] = "Gratis"
} else if self.tradeSwitch.on {
post["tradeOption"] = "Te ruil"
}
let firebasePost = DataService.ds.REF_LISTS.childByAutoId()
firebasePost.setValue(post)
}
#IBAction func postListItem(sender: AnyObject) {
if let addTitle = addTitle.text where addTitle != "", let addDescription = addDescription.text where addDescription != "", let addLocation = addLocation.text where addLocation != "" {
dispatch_async(backgroundQueue, {
self.postToFirebase()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let listVC = storyboard.instantiateViewControllerWithIdentifier("TBC") as! UITabBarController
listVC.selectedIndex = 1
self.presentViewController(listVC, animated: false, completion: nil)
})
})
}
}
func textViewDidBeginEditing(textView: UITextView) {
placeholderLbl.hidden = true
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text == "" {
placeholderLbl.hidden = false
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
and the swift file to configure the cell:
import UIKit
import Alamofire
import Firebase
class ListCell: UITableViewCell {
#IBOutlet weak var listImg: UIImageView!
#IBOutlet weak var listTitle: UILabel!
#IBOutlet weak var listTradeOption: UILabel!
#IBOutlet weak var listLocation: UILabel!
#IBOutlet weak var headImg: UIImageView!
var list: List!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func retrieveImages() {
DataService.ds.REF_LISTS.observeEventType(FEventType.Value, withBlock: { snapshot in
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
let image = snap.value.objectForKey("images") as! String
let decodedData = NSData(base64EncodedString: image, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
self.headImg.image = decodedImage
}
}
})
}
func configureCell(list: List) {
self.list = list
self.listTitle.text = list.listTitle
self.listTradeOption.text = list.listTradeOption
self.listLocation.text = list.listLocation
retrieveImages()
}
}
also the list Model file:
import Foundation
import Firebase
class List {
private var _listTitle: String!
private var _listDescription: String!
private var _listTradeOption: String!
private var _listLocation: String!
private var _listImageURL: String?
private var _listKey: String!
private var _listRef: Firebase!
var listTitle: String? {
return _listTitle
}
var listDescription: String? {
return _listDescription
}
var listTradeOption: String? {
return _listTradeOption
}
var listLocation: String? {
return _listLocation
}
var listKey: String {
return _listKey
}
var listImageURL: String? {
return _listImageURL
}
init(title: String, description: String, tradeOption: String, location: String, listImageURL: String?) {
self._listTitle = title
self._listDescription = description
self._listTradeOption = tradeOption
self._listLocation = location
self._listImageURL = listImageURL
}
init(listKey: String, dictionary: Dictionary<String, AnyObject>) {
self._listKey = listKey
if let title = dictionary ["title"] as? String {
self._listTitle = title
}
if let desc = dictionary ["description"] as? String {
self._listDescription = desc
}
if let trade = dictionary ["tradeOption"] as? String {
self._listTradeOption = trade
}
if let loc = dictionary ["location"] as? String {
self._listLocation = loc
}
if let imgUrl = dictionary["images"] as? String {
self._listImageURL = imgUrl
}
self._listRef = DataService.ds.REF_LISTS.childByAppendingPath(self._listKey)
}
}
i've got also a DataServicefile, where i create a user by unique ID with this code:
var REF_USER_CURRENT: Firebase {
let uid = NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID) as! String
let user = Firebase(url: "\(REF_BASE)").childByAppendingPath("users").childByAppendingPath(uid)
return user!
}
func createFirebaseUser(uid: String, user: Dictionary<String, String>) {
REF_USERS.childByAppendingPath(uid).setValue(user)
}
i know it's a lot but maybe the best way to help :)
Try editing this in List Cell
var imageURL = String()
func retrieveImages() {
let decodedData = NSData(base64EncodedString: imageURL, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
self.headImg.image = decodedImage
}
func configureCell(list: List) {
self.list = list
self.listTitle.text = list.listTitle
self.listTradeOption.text = list.listTradeOption
self.listLocation.text = list.listLocation
self.imageURL = list.listImageURL //you already had the image url for that specific cell
retrieveImages()
}
Storing and accessing images using base64String in firebase is not an
efficient way, instead of that we can use FirebaseStorage (Google cloud storage
bucket) for uploading images to Firebase and it will provide us
download URL for a particular image. We can store that URL into our database simply in a string format and access it whenever we
required and then download the corresponding image from that URL by
using SDWebImage.
Refer below link for integrating FirebaseStorage into your project: https://firebase.google.com/docs/storage/ios/upload-files

CoreData and Swift: contents gets swapped

I am new to swift and have a problem with CoreData: I can save and load to and from my CoreData store. But when I load the saved data from CoreData the data has been rearranged. I don't want this to happen. How do I solve this?
My code is this:
Meetings.swift
import Foundation
import CoreData
class Meetings: NSManagedObject {
#NSManaged var meetingTimeLeft: NSNumber
#NSManaged var title: String
#NSManaged var date: NSDate
#NSManaged var timeFrom: NSDate
#NSManaged var timeTo: NSDate
#NSManaged var timeFromActual: NSDate
#NSManaged var timeToActual: NSDate
#NSManaged var location: String
#NSManaged var locationRoom: String
#NSManaged var meetingGoals: String
#NSManaged var purpose: String
#NSManaged var averageHourlyCost: NSNumber
#NSManaged var completed: NSNumber
#NSManaged var durationActual: NSNumber
#NSManaged var durationPlanned: NSNumber
#NSManaged var persons: NSSet
#NSManaged var agendas: NSSet
#NSManaged var minutes: NSSet
#NSManaged var relationship: NSManagedObject
#NSManaged var startSetting: StartSetting?
}
extension Meetings {
func addPer(value: Person) {
self.mutableSetValueForKey("persons").addObject(value)
}
func removePer(value: Person) {
self.mutableSetValueForKey("persons").removeObject(Person)
//self.mutableSetValueForKey("persons").addObject(value)
}
func getPer() -> [Person] {
var persons: [Person]
persons = self.persons.allObjects as! [Person]
return persons
}
func addAgenda(value: AgendaItem) {
self.mutableSetValueForKey("agendas").addObject(value)
}
func removeAgenda(value: AgendaItem) {
self.mutableSetValueForKey("agendas").removeObject(AgendaItem)
//self.mutableSetValueForKey("persons").addObject(value)
}
func getAgenda() -> [AgendaItem] {
var agendas: [AgendaItem]
agendas = self.agendas.allObjects as! [AgendaItem]
return agendas
}
func getAgendaItem(i: Int) -> AgendaItem {
var agendas: [AgendaItem]
agendas = self.agendas.allObjects as! [AgendaItem]
let agendaItem = agendas[i]
return agendaItem
}
}
person.swift
import Foundation
import CoreData
class Person: NSManagedObject {
#NSManaged var name: String
#NSManaged var email: String
#NSManaged var phone: NSNumber
#NSManaged var title: String
#NSManaged var company: String
#NSManaged var photo: NSData
#NSManaged var meeting: Meetings
}
AgendaItem.swift
import Foundation
import CoreData
class AgendaItem: NSManagedObject {
#NSManaged var agendaItemTitle: String
#NSManaged var presenter: String
#NSManaged var durationPlanned: NSNumber
#NSManaged var durationActual: NSNumber
#NSManaged var filePresentation: NSData
#NSManaged var fileSupporting: NSData
#NSManaged var agendaTimeStart: NSDate
#NSManaged var meeting: Meetings
}
when saving i do like this:
internal var meetingsModels = [Meetings]()
public let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
managedObjectContext?.deleteObject(meetingsModels[meetingsIndexPassed.row]) meetingsModels.removeAtIndex(meetingsIndexPassed.row)
let entityDescription = NSEntityDescription.entityForName("Meetings", inManagedObjectContext: managedObjectContext!)
let entityDescription2 = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext!)
let entityDescription3 = NSEntityDescription.entityForName("AgendaItem", inManagedObjectContext: managedObjectContext!)
let meetings = Meetings(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
meetings.title = meetingTitle_txt.text!
meetings.date = lDate
meetings.timeFrom = lStartTime
meetings.timeTo = lEndTime
meetings.location = address_txt.text!
meetings.purpose = details[0]
meetings.meetingGoals = details[1]
meetings.locationRoom = details[2]
meetings.durationPlanned = meetingsEditPassed.durationPlanned
meetings.completed = false
for var i = 0; i < personsEdit.count; i++ {
let person = Person(entity: entityDescription2!, insertIntoManagedObjectContext: managedObjectContext)
person.name = personsEdit[i].name
person.email = personsEdit[i].email
person.title = personsEdit[i].title
person.company = personsEdit[i].company
person.phone = personsEdit[i].phone
meetings.addPer(person)
}
for var i = 0; i < agendaEdit.count; i++ {
let agenda = AgendaItem(entity: entityDescription3!, insertIntoManagedObjectContext: managedObjectContext)
agenda.agendaItemTitle = agendaEdit[i].agendaItemTitle
//print(agendaEdit[i].agendaItemTitle)
agenda.presenter = agendaEdit[i].presenter
agenda.durationPlanned = agendaEdit[i].durationPlanned
meetings.addAgenda(agenda)
}
do {
try managedObjectContext?.save()
} catch let error1 as NSError {
print("\(error1)")
}
meetingsModels.append(meetings)
when loading i do this:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let fetchRequest = NSFetchRequest(entityName:"Meetings")
//fetchRequest.sortDescriptors = nil
//3
let fetchedResults: [Meetings]
do {
try
fetchedResults = (managedContext.executeFetchRequest(fetchRequest) as? [Meetings])!
if let results: [Meetings] = fetchedResults {
var temp = [Meetings]()
var temp2 = [Meetings]()
for tmp: Meetings in results {
temp.append(tmp)
if tmp.completed.boolValue {
temp2.append(tmp)
}else {
}
}
meetingsModels = temp
meetingsModels2 = temp2
} else {
}
} catch let error1 as NSError {
print("could not fetch meetings: \(error1), \(error1.userInfo)")
}
}
i hope that some of you can help me.
Your meetings data is being "rearranged" just because your Meetings don't belong to any ordered relationship. I'm not able to run your code on my side. However, I can recommend you one of the following:
Use ordered relations any time you want to make sure the order of
data is preserved any time you fetch it.
Use the
sortDescriptors property on your fetch requests. When you
create one, you can add a sort descriptor to it in order to
arrange data.