I have an Objective-C app that integrates with Google Analytics. Now, I'm trying to integrate an app written in Swift.
There's my Objective-C Code:
- (void) signInGoogleAnalytics {
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
// You only need to set User ID on a tracker once. By setting it on the tracker, the ID will be
// sent with all subsequent hits.
[tracker set:kGAIUserId
value:self.txtStoreCode.text];
NSString *dimensionUsuarioLogado = [NSString stringWithFormat:#"%#", _txtEmployee.text];
NSString *dimensionLoja = [NSString stringWithFormat:#"%#", _txtStoreCode.text];
[tracker send:[[[GAIDictionaryBuilder createScreenView] set:dimensionUsuarioLogado
forKey:[GAIFields customDimensionForIndex:1]] build]];
[tracker send:[[[GAIDictionaryBuilder createScreenView] set:dimensionLoja
forKey:[GAIFields customDimensionForIndex:2]] build]];
}
and I'm trying in swift
func signInGoogleAnalytics() {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIUserId, value: txtStore.text)
var dimensionUsuarioLogado = "\(txtUser.text)"
var dimensionLoja = "\(txtStore.text)"
tracker.send(GAIDictionaryBuilder.createScreenView().set(dimensionUsuarioLogado, forKey: GAIFields.customDimension(forIndex: 1)).build())
tracker.send(GAIDictionaryBuilder.createScreenView().set(dimensionLoja, forKey: GAIFields.customDimension(forIndex: 1)).build())
}
but I'm getting GAIFields has no member customDimension. Then, how should be the code in Swift?
It worked for me:
func signInGoogleAnalytics() {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIUserId, value: txtStore.text)
let dimensionUsuarioLogado = "\(txtUser.text)"
let dimensionLoja = "\(txtStore.text)"
tracker.send(GAIDictionaryBuilder.createScreenView().set(dimensionUsuarioLogado, forKey: GAIFields.customDimensionForIndex(1)).build() as NSDictionary as [NSObject : AnyObject])
tracker.send(GAIDictionaryBuilder.createScreenView().set(dimensionLoja, forKey: GAIFields.customDimensionForIndex(2)).build() as NSDictionary as [NSObject : AnyObject])
}
I was tracking custom exception with custom dimension:
//MARK:- CUSTOM EXCEPTION TRACKING
func doTrackCustomExceptionWithGA(message:String, customDimensionValue:String, isFatal:Bool = false) {
guard let tracker = GAI.sharedInstance()?.defaultTracker else { return }
guard let exceptionBuilder = GAIDictionaryBuilder.createException(withDescription: message, withFatal: NSNumber(value: isFatal)) else { return }
if !customDimensionValue.isEmpty {
exceptionBuilder.set(customDimensionValue, forKey: GAIFields.customDimension(for: 15))
}
guard let build = exceptionBuilder.build() as? [AnyHashable : Any] else { return }
tracker.send(build)
// ADDING DUMMY EVENT TO TRACK PREVIOUS EVENT QUICKLY, AS GA EVENTS ARE TRACKED ON NEXT EVENT CALLS
// BELOW CODE IS OPTIONAL
let event = GAIDictionaryBuilder.createScreenView()
tracker.send(event?.build() as! [NSObject: Any])
}
Related
I'm asking this question because all answers I've found online are either outdated or not working for me.
I'm working with a customers framework and for some reason they require me to use CocoaLumberjack in the project so any suggestions on other Log-tools are useless for me, at least for this project, thank you in advance for understanding
The question:
How do I get the logs from users? I am not that familiar to logging so this is all new to me.
I've written some code with the help of numerous SO-answers and CocoaLumberjacks documentation on Github.
I'm pretty sure that I am actually logging because I can get the logs from Xcode when I run my app on a real device by doing: Xcode -> Window -> Devices and Simulators -> Select the device (and app) -> Download Container.
From the container I can see the logs. But how can I see the logs from user that are not physically here with their device?
AppDelegate.swift :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let formatter = LogFormatter()
DDTTYLogger.sharedInstance.logFormatter = formatter
return true
}
my logformatter is from StackOverflow https://stackoverflow.com/a/14000342/4189589
class LogFormatter: NSObject, DDLogFormatter {
let dateFormatter: DateFormatter
static let sharedInstance = LogFormatter()
override init() {
dateFormatter = DateFormatter()
dateFormatter.formatterBehavior = .behavior10_4
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:SSS"
DDLog.add(DDOSLogger.sharedInstance) // Uses os_log
let fileLogger: DDFileLogger = DDFileLogger() // File Logger
fileLogger.rollingFrequency = 60 * 60 * 24 // 24 hours
fileLogger.logFileManager.maximumNumberOfLogFiles = 7
DDLog.add(fileLogger)
DDLogDebug("Debug")
DDLogVerbose("Verbose")
DDLogInfo("Info")
DDLogWarn("Warn")
DDLogError("Error")
super.init()
}
func format(message logMessage: DDLogMessage) -> String? {
let dateAndTime = dateFormatter.string(from: logMessage.timestamp)
return "\(dateAndTime) [\(logMessage.fileName):\(logMessage.line)]: \(logMessage.message)"
}
var ddFileLogger: DDFileLogger!
var logFileDataArray: [NSData] {
get {
let logFilePaths = ddFileLogger.logFileManager.sortedLogFilePaths
var logFileDataArray = [NSData]()
for logFilePath in logFilePaths {
let fileURL = NSURL(fileURLWithPath: logFilePath)
if let logFileData = try? NSData(contentsOf: fileURL as URL, options: NSData.ReadingOptions.mappedIfSafe) {
// Insert at front to reverse the order, so that oldest logs appear first.
logFileDataArray.insert(logFileData, at: 0)
}
}
return logFileDataArray
}
}
}
And then I want to email the logs with a button (from same SO-answer)
func emailLogsTo(email: String) {
if MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
// Configure the fields of the interface.
composeVC.setToRecipients([email])
composeVC.setSubject("Feedback for app")
composeVC.setMessageBody("", isHTML: false)
let attachmentData = NSMutableData()
for logFileData in LogFormatter.sharedInstance.logFileDataArray {
attachmentData.append(logFileData as Data)
}
composeVC.addAttachmentData(attachmentData as Data, mimeType: "text/plain", fileName: "diagnostic.log")
self.present(composeVC, animated: true, completion: nil)
} else {
// Tell user about not able to send email directly.
}
}
What happens when I call the function to send the email is that I get an "unexpectedly found nil while implicitly unwrapping an Optional value"-error on
let logFilePaths = ddFileLogger.logFileManager.sortedLogFilePaths
in LogFormatter()
What am I doing wrong?
I only have it in Obj-C I'm afraid:
NSMutableData *logData = [NSMutableData data];
for (NSData *logFileData2 in [self.utilities logfileData]) {
[logData appendData:logFileData2];
}
[picker addAttachmentData:logData mimeType:#"text/plain" fileName:#"logs.txt"];
Then in my utilities class:
- (NSMutableArray *)logfileData {
NSUInteger maximumLogFilesToReturn = MIN(fileLogger.logFileManager.maximumNumberOfLogFiles, 10);
NSMutableArray *logFiles = [NSMutableArray arrayWithCapacity:maximumLogFilesToReturn];
DDFileLogger *logger = fileLogger;
NSArray *sortedLogFileInfos = [logger.logFileManager sortedLogFileInfos];
for (NSUInteger i = 0; i < MIN(sortedLogFileInfos.count, maximumLogFilesToReturn); i++) {
DDLogFileInfo *logFileInfo = [sortedLogFileInfos objectAtIndex:i];
NSData *fileData = [NSData dataWithContentsOfFile:logFileInfo.filePath];
[logFiles addObject:fileData];
}
return logFiles;
}
So maybe for you:
var logFileDataArray: [NSData] {
get {
let sortedLogFileInfos = ddFileLogger.logFileManager.sortedLogFileInfos
var logFileDataArray = [NSData]()
for logFileInfo in sortedLogFileInfos {
if let logFileData = try? NSData(contentsOf: logFileInfo.filePath as String, options: NSData.ReadingOptions.mappedIfSafe) {
// Insert at front to reverse the order, so that oldest logs appear first.
logFileDataArray.insert(logFileData, at: 0)
}
}
return logFileDataArray
}
}
We are facing issues while integrating coredata with our chat application. Please help us to resolve the issue. We tried to figure out each issue individually but sometimes it gets fixed and then shows up randomly. We are tring to fix it from last 1 week.
Our setup stack
We are using sockets library to for real time chatting. To persist the data we are using core-data. Our application is supporting iOS 8 and above so we can't use PersistenceContainer so to workoround this we are using BNRCoreDataStack [url: https://github.com/bignerdranch/CoreDataStack] which is similiar to what PersistenceContainer does.
Also to display chat we are using IGListKit and we have created viewModels to avoid sending mutable coredata objects to IGLIstkit as IGListkit works fine with immutable model. Also we have used this setup to create our own viewModels [url: https://github.com/Instagram/IGListKit/blob/master/Guides/Working%20with%20Core%20Data.md]
issues we are facing
1] Constraint validation failure
2] FetchResult controller crash issue
crash-log:
2018-07-19 21:41:36.515153+0530 Toppr Doubts[62803:2359707] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3698.54.4/UITableView.m:2012
2018-07-19 21:41:36.517093+0530 Toppr Doubts[62803:2359707] [error] error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (60) must be equal to the number of rows contained in that section before the update (50), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). with userInfo (null)
CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (60) must be equal to the number of rows contained in that section before the update (50), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). with userInfo (null)
3] Illegal attempt to establish a relationship 'lastMessage' between objects in different contexts
Below is our CoreDataModel, we are not using any abstract entity for Message as we came to know this could cause lot of performance issues.
Session Entity
We are creating object in fromJSON method and setup is same for rest of the entities. Also I am sharing LastMessage Entity to show the way we are integrating relationships, again same for others
public class Session: NSManagedObject {
class func fromJSON(_ json: JSON, moc: NSManagedObjectContext) -> Session? {
if let entityDescription = NSEntityDescription.entity(forEntityName: "Session", in: moc) {
// Object creation
let object = Session(entity: entityDescription, insertInto: moc)
object.internalIdentifier = json[kSessionIdKey].int64Value
if let date = json[kSessionStartedOnKey].dateTime as NSDate? {
object.startedOn = date
}
if let date = json[kSessionEndedOnKey].dateTime as NSDate? {
object.endedOn = date
}
object.statusType = SessionStatus(rawValue: json[kSessionStatusKey].stringValue).map { $0.rawValue } ?? SessionStatus.none.rawValue
object.stateType = SessionState(rawValue: json[kSessionStateKey].stringValue).map { $0.rawValue } ?? SessionState.none.rawValue
if let ratingDict = json[kSessionRatingKey].dictionaryObject {
if let rating = ratingDict["student"] as? Int {
object.rating = rating
}
}
object.subjectID = json[kSessionSubjectKey]["id"].intValue
// Subjects are already stored need to fetch and assign
let subjectFetchRequest: NSFetchRequest<Subject> = Subject.fetchRequest()
subjectFetchRequest.predicate = NSPredicate(format: "internalIdentifier == %d", Int64(json[kSessionSubjectKey]["id"].intValue))
do {
if let subject = try moc.fetch(subjectFetchRequest).first {
object.subject = subject
}
} catch let erroe as NSError {
Logger.log.error(error)
}
// Student Object initialisation
if json[kSessionStudentKey] != JSON.null {
if let student = Student.fromJSON(json[kSessionStudentKey], moc: moc) {
object.student = student
}
}
// Tutor Object initialisation
if json[kSessionTutorKey] != JSON.null {
if let tutor = Tutor.fromJSON(json[kSessionTutorKey], moc: moc) {
object.tutor = tutor
}
}
// LastMessage Object initialisation
if json[kSessionLastMessageKey] != JSON.null {
if let lastMessage = LastMessage.fromJSON(json[kSessionLastMessageKey], moc: moc) {
object.lastMessage = lastMessage
} else {
return nil
}
}
return object
}
return nil
}
}
LastMessage
public class LastMessage: NSManagedObject, Message {
class func fromJSON(_ json: JSON, moc: NSManagedObjectContext) -> LastMessage? {
if let entityDescription = NSEntityDescription.entity(forEntityName: "LastMessage", in: moc) {
let object = LastMessage(entity: entityDescription, insertInto: moc)
object.id = json[kMessageIdKey].intValue
object.body = json[kBodyKey].stringValue
object.type = MessageType(rawValue: json[kTypeKey].stringValue) ?? MessageType.none
object.doubtTag = json[kDoubtTagKey].stringValue
if json[kAttachmentKey] != JSON.null {
if let attachment = Attachment.fromJSON(json[kAttachmentKey], moc: moc) {
object.attachment = attachment
}
}
if let date = json[kSentOnKey].dateTime as NSDate? {
object.sentOn = date
}
if json[kSentByKey] != JSON.null {
if let sentBy = SentBy.fromJSON(json[kSentByKey], moc: moc) {
object.sentBy = sentBy
}
}
object.deliveryState = DeliveryState(rawValue: json[kDeliveryStateKey].stringValue) ?? DeliveryState.none
object.sessionId = json[kSessionIdKey].intValue
return object
}
return nil
}
}
Get User State
Helps us fetch data for subject and live chat.
static func getUserState(completion:#escaping (_ success: Bool) -> Void) {
SocketManager.sharedInstance.send(eventName: .userState) { (response) in
guard !response.isError() else { return completion(false) }
// Coredatastack
guard let coreDataStack = (UIApplication.shared.delegate as! AppDelegate).coreDataStack else { return }
let wmoc = coreDataStack.newChildContext()
// Save Subject and Live Sessions
let subjects = response.result["subjects"].arrayValue.flatMap({ Subject.fromJSON($0, moc: wmoc) })
let sessions = response.result["live_sessions"].arrayValue.flatMap({ Session.fromJSON($0, moc: wmoc) })
if sessions.isNotEmpty || subjects.isNotEmpty {
CoreDataStack.batchUpdate(moc: wmoc, completion: {
NotificationCenter.default.post(name: NSNotification.Name("didUpdateUserState"), object: nil)
completion(true)
})
}
completion(false)
}
}
Get Previous Session
Helps us fetch data for inactive chats. We are getting problem in this while storing sessions
static func getPreviousSessions(isLoadingMore: Bool, completion: #escaping (_ success: Bool,_ isMore: Bool)->Void) {
guard let coreDataStack = (UIApplication.shared.delegate as! AppDelegate).coreDataStack else { return }
let wmoc = coreDataStack.newChildContext()
var sessionID = 0
// TODO: - Need to implement last sessionID from CoreData
if isLoadingMore {
// Get Sessions with Status == closed order by sessionID asc
let archiveSession = Session.filterArchivedSessions(moc: wmoc)
let sortedArchiveSession = archiveSession?.sorted(by: { $0.0.id < $0.1.id })
// Get last sessionID
if let lastSessionID = sortedArchiveSession?.first?.id {
sessionID = lastSessionID
}
}
let request: [String: Any] = [ "last_session_id": sessionID ]
SocketManager.sharedInstance.send(request, eventName: .getPreviousSessions) { (response) in
if response.result.isEmpty {
completion(false, false)
} else {
let sessions = response.result["sessions"].arrayValue.flatMap({ Session.fromJSON($0, moc: wmoc) })
if sessions.isNotEmpty {
CoreDataStack.batchUpdate(moc: wmoc)
} else {
for session in sessions { wmoc.delete(session) }
}
if let isMore = response.result["is_more_server"].bool {
completion(true, isMore)
}
}
}
}
In the above image every session is suppose to have one last message and one subject. But as you can see, there are no last messages and some session have subjects as null
CoreDataStack+Extension
To Save data directly to Store
extension CoreDataStack {
// This method will add or update a CoreData's object.
static func batchUpdate(moc: NSManagedObjectContext? = nil, completion: (()-> Void)? = nil) {
guard let moc = moc, moc.hasChanges else { return }
if #available(iOS 10.0, *) {
moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
}
do {
try moc.performAndWaitOrThrow {
try moc.saveContextToStoreAndWait()
DispatchQueue.main.async {
completion?()
}
}
} catch {
print("Error creating initial data: \(error)")
}
}
}
NSFetchedResultsController Setup
lazy var archievedSessionFRC: NSFetchedResultsController<Session> = {
guard let coreDataStack = (UIApplication.shared.delegate as! AppDelegate).coreDataStack else { return NSFetchedResultsController() }
// Create Fetch Request
let fetchRequest: NSFetchRequest<Session> = Session.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "internalIdentifier", ascending: false)]
fetchRequest.predicate = NSPredicate(format: "statusType = %#", "closed")
let archievedSessionFRC = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: coreDataStack.mainQueueContext,
sectionNameKeyPath: nil,
cacheName: nil)
archievedSessionFRC.delegate = self
return archievedSessionFRC
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
do {
try archievedSessionFRC.performFetch()
if let sessions = archievedSessionFRC.fetchedObjects {
self.previousSessions = sessions
}
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.localizedDescription)")
}
}
// MARK: - NSFetchedResultsControllerDelegate
extension HomeVC: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
if let indexPath = newIndexPath {
self.tableView.insertRows(at: [indexPath], with: .automatic)
}
case .delete:
if let indexPath = indexPath {
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
case .move:
if let indexPath = indexPath , let newIndexPath = newIndexPath {
self.tableView.moveRow(at: indexPath, to: newIndexPath)
}
case .update:
if let indexPath = indexPath {
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.endUpdates()
}
}
Thanks in Advance
First of all, I am new in this, so please do not make fun of me :)
Basically, I am trying to show and Image of a product but if the client refuses the product this item will not appear on his account. That is why I am creating another table Rejected (setAcceptedOrRejected) where I put the ID of the product and the Id of the client so I wont see the item he rejected before.
What I tried here it was to get the List (Good) with all the items and the (Bad) with the rejected items. Then compare it to display the picture of the item again.
My problem is that I want to show only 1 picture at the time, if the client refuses then it will show the next one and so on but it wont show that picture again.
I hope you can really help me with this one.
Thank you
func updateImage() {
createListProductsBad ()
var badnot = ""
for bad2 in listProductsBad{
badnot = bad2
}
Database.database().reference().child("Products").child(bad2)queryOrderedByKey().observe(.childAdded, with: { snapshot in
let userInfo = snapshot.value as! NSDictionary
let storageRef = Storage.storage().reference(forURL: profileUrl)
storageRef.downloadURL(completion: { (url, error) in
do {
let data = try Data(contentsOf: url!)
let image = UIImage(data: data as Data)
self.productPhoto.image = image
}
catch _ {
print("error")
}
})
})
}
func setAcceptedOrRejected() {
let notThankyou = [ "ProductID": ProductId,
"UserID": userUID
] as [String : Any]
self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.refProducts.child("Rejected").childByAutoId().setValue(notThankyou)
}
func createListProductsGood () {
Database.database().reference().child("Products").queryOrderedByKey().observe(.childAdded, with: { snapshot in
if !snapshot.exists() { return }
let userInfo = snapshot.value as! NSDictionary
let goodID = String(snapshot.key)
for prod in self.listProductsBad{
if (prod == goodID){
print("Not good **********************")
}else{
if (goodID != "" ){
self.listProductsGood.append(prod)
}
}
}
})
}
func createListProductsBad () {
Database.database().reference().child("Rejected").queryOrderedByKey().observe(.childAdded, with: { snapshot in
let userInfo = snapshot.value as! NSDictionary
let currentID = userInfo["UserID"] as! String
let badProduct = userInfo["ProductID"] as! String
if (self.userUID == currentID ){
self.listProductsBad.append(badProduct)
}
})
}
}
//These can also be swift's dictionaries, [String: AnyObject] or possibility arrays if done correctly. All depends on your style of programming - I prefer NSDictionaries just because.
let availableKeys: NSMutableDictionary = [:]
let rejectedKeys: NSMutableDictionary = [:]
//Might be a better way for you. Depends on what you are looking for.
func sortItems2() -> NSMutableDictionary{
for rejKey in rejectedKeys.allKeys{
//Removes if the rejected key is found in the available ones
availableKeys.remove(rejKey)
}
return availableKeys
}
I have recently been updating a library to swift 3.0 as a relatively new swift dev. I get a error where I cannot cast __NSCFDictionary to a NSArray format. How could I convert __NSCFDictionary to NSArray format in swift with a example please?
This is the current function I am converting
method(name: "login", params: NSArray(arrayLiteral: params)) //fails casting here
guard let e = error , (e.isValid == true) else {
if let user = params["user"] as? AnyObject {
if let email = user["email"] {
self.userData.set(email, forKey: DDP_EMAIL)
}
if let username = user["username"] {
self.userData.set(username, forKey: DDP_USERNAME)
}
}
if let data = result as? NSDictionary,
let id = data["id"] as? String,
let token = data["token"] as? String,
let tokenExpires = data["tokenExpires"] as? NSDictionary {
let expiration = dateFromTimestamp(containedIn: tokenExpires)
self.userData.set(id, forKey: DDP_ID)
self.userData.set(token, forKey: DDP_TOKEN)
self.userData.set(expiration, forKey: DDP_TOKEN_EXPIRES)
}
self.userMainQueue.addOperation() {
if let c = callback { c(result, error) }
self.userData.set(true, forKey: DDP_LOGGED_IN)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: DDP_USER_DID_LOGIN), object: nil)
if let _ = self.delegate {
self.delegate!.ddpUserDidLogin(user: self.user()!)
}
}
return
}
log.debug("Login error: \(e)")
if let c = callback { c(result, error) }
}
I am trying to check the id of a record before I put it into the array, using xcode swift
here is the code. But, i get the following error
Notifications.swift:50:46: Cannot convert value of type 'String?!' to expected argument type 'Notifications'
on this line
*if (readRecordCoreData(result["MessageID"])==false)*
Please can some one help to explain this error
import CoreData
struct Notifications{
var NotifyID = [NSManagedObject]()
let MessageDesc: String
let Messageid: String
init(MessageDesc: String, Messageid:String) {
self.MessageDesc = MessageDesc
self.Messageid = Messageid
// self.MessageDate = MessageDate
}
static func MessagesWithJSON(results: NSArray) -> [Notifications] {
// Create an empty array of Albums to append to from this list
var Notification = [Notifications]()
// Store the results in our table data array
if results.count>0 {
for result in results {
//get fields from json
let Messageid = result["MessageID"] as! String
let MessageDesc = result["MessageDesc"] as? String
let newMessages = Notifications(MessageDesc: MessageDesc!, Messageid:Messageid)
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
}
}
return Notification
}
//check id
func readRecordCoreData(Jsonid: String) -> Bool {
var idStaus = false
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ItemLog")
//3
do {
let resultsCD = try! managedContext.executeFetchRequest(fetchRequest)
if (resultsCD.count > 0) {
for i in 0 ..< resultsCD.count {
let match = resultsCD[i] as! NSManagedObject
let id = match.valueForKey("notificationID") as! String
if (Jsonid as String! == id)
{
idStaus = true
}
else{
idStaus = false
}
}
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
return idStaus
}
One of your methods is static and the other one is not :
func readRecordCoreData(Jsonid: String) -> Bool
static func MessagesWithJSON(results: NSArray) -> [Notifications]
Depending on what you want to accomplish you could declare both static, none, or replace
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
By
//check with id's from core data
if (Notifications.readRecordCoreData(Messageid)==false)
{
Notification.append(newMessages)
}
Not sure if the code will work past compilation however as there are many readability issues