Swift 3 timed event - ios

I have the following:
let processURLS = processingViewController()
Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(processURLS.getURLsToSend),
userInfo: nil,
repeats: true)
When this event is triggered, I received the following error and I'm not sure why this doesn't work
2016-11-09 14:47:00.504932 AcumenJLR[3414:905978] * Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[AcumenJLR.homeViewController getURLsToSend]: unrecognized selector
sent to instance 0x100d25c60'
* First throw call stack: (0x1816721c0 0x1800ac55c 0x181679278 0x181676278 0x18157059c 0x18215c8f8 0x1816208f4 0x181620608
0x18161fec4 0x18161dac0 0x18154c048 0x182fd2198 0x1875372fc
0x187532034 0x100114620 0x1805305b8) libc++abi.dylib: terminating with
uncaught exception of type NSException
Here is the getURLsToSend method
func getURLsToSend () {
//create a fetch request, telling it about the entity
let fetchRequest: NSFetchRequest<URLsToSend> = URLsToSend.fetchRequest()
let context = getContext()
do {
//Get results
let searchResults = try getContext().fetch(fetchRequest)
print ("num of results = \(searchResults.count)")
//You need to convert to NSManagedObject to use 'for' loops
for urls in searchResults as [NSManagedObject] {
//get the Key Value pairs (although there may be a better way to do that...
//print("\(urls.value(forKey: "url"))")
let currentURL = urls.value(forKey: "url")!
//print(urls.value(forKey: "url")!)
completeLoadAction(urlString: currentURL as! String) { code in
if (code == 200){
context.delete(urls)
}
}
}
} catch {
print("Error with request: \(error)")
}

According to the target / action pattern the method specified in selector must be declared in the class specified in target in this case the current class self.
Either change the target or implement the method in self.

May be you have some paramter in method but you are not sending any value from there

Related

CoreData crashes when saving Main Object Context

When I move my application to the background, CoreData seems to crash as soon as I save the mainObjectContext. In the console I am seeing the following error:
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x6000064c7ac0> , -[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000319de00 with userInfo of (null)
The method to save the main object context is implemented like this:
func save() {
if mainManagedObjectContext.hasChanges {
mainManagedObjectContext.performAndWait {
do {
try mainManagedObjectContext.save()
} catch {
NotificationCenter.default.post(name: .ManagedObjectContextSaveError, object: nil)
}
}
NotificationCenter.default.post(name: .MainManagedObjectContextSaved, object: nil)
}
}
This method is called from AppDelegate.applicationWillResignActive(_:)
I am not sure why encodeWithCoder is being called here and why it would crash.
In fact, I am not even sure how to further troubleshoot it from here.

Swift Parse Live query - crashing when subscription comes across new object with PFFile

I am creating a swift 3 parse live query messaging application. When a picture is sent, if the subscription gets the new message then i get the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI getDataInBackgroundWithBlock:]: unrecognized selector sent to instance 0x60000106e9c0'
When I reload the page and the original query gets the picture it works fine.
Here is my code
this is my original query that I subscribe to
var messagesQuery: PFQuery<Message> {
return (Message.query()?
.whereKey("roomName", equalTo: chatName)
.order(byAscending: "createdAt")) as! PFQuery<Message>
Here is my subscription to that query
func subscribeToUpdates() {
subscription = liveQueryClient
.subscribe(messagesQuery)
.handle(Event.created) { _, message in
self.messages.append(message)
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
})
}
}
Here is the code causing the crash to occur (again only when the message is recieved via live query subscription rather than traditional query)
(message.image)?.getDataInBackground(block: { (data:Data?, error:Error?) in
if error == nil {
cell.messageImageView.image = UIImage(data: data!)
}
})

Core Data: Correct way to update within a NSUrlRequest

I have a NSUrlRequest in which i call a method User.updateMyObject(id: NSNumber, name: String). Object User has the static properties:
static let appDelegate = UIApplication.shared.delegate as! AppDelegate
static let MOC = appDelegate.managedObjectContext
And several methods for updating/creating/deleting objects.
Now, I have read that you shouldn't use you MOC on different threads. And as far as I know a NSUrlRequest runs asynchronously. How would I then go about calling MyObject.updateMyObject(id: NSNumber, name: String)?
I sometimes get the error:
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
My request looks like this:
let session = URLSession.shared
// The singleton shared session is for basic requests.
// Data tasks send and receive data using NSData objects.
// Data tasks are intended for short, often interactive requests to a server.
let task = session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
//JSon parsing
MyObject.updateMyObject(id: NSNumber, name: String)
}
task.resume()
MyObject.updateMyObject(id: NSNumber, name: String) looks like this:
static func updateMyObject(id: NSNumber, name: String) {
let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MyObject")
let resultPredicate = NSPredicate(format: "id = \(id)")
request.predicate = resultPredicate
do {
let result = try User.MOC.fetch(request).first as! MyObject
result.name = name
User.appDelegate.saveContext()
}
catch {
print("User.updateMyObject: error.")
}
}
This is why the perform and performAndWait methods exist on NSManagedObjectContext-- so that you can safely use the context on different threads. You should use one of them here.
In general, any time you touch anything Core Data related, you need to wrap that code in a call to one of these two methods. The methods take a closure as an argument; put your Core Data code in that closure. The only exception to this rule, ever, is if you used mainQueueConcurrencyType and you know that your code is running on the main queue.

Core Data - Swift - Catch "keypath not found in entity" error

I am trying to catch an error when I execute a FetchRequest with a wrong/inexistent Key/Keypath but the app still crashes.
This is how I created the NSPredicate:
let pred = NSPredicate(format: "(\("WRONGKEY") = %#)", equalTo)
let request = NSFetchRequest()
request.predicate = pred
request.entity = MyEntityDescription
(WRONGKEY is a parameter that could be wrong/nonexistent in the Core Data schema)
And this is the line that cause the error:
var objects = managedContext?.executeFetchRequest(request, error: &error) as? [Model]
This is the error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath keyX not found in entity < NSSQLEntity EN id=2 >'
* First throw call stack: .....
So I have tried to use:
if let objects = managedContext?.executeFetchRequest(request, error: &error) as? [Model] {
println("okkkkkkkk")
} else {
println("error")
}
but doesn't work.
I have tried:
if(error != nil) {
but doesn't work either.
Is there a way to catch the error and avoid that the app crashes?
In Swift, try-catch isn't available. You can switch back to Objective-C, or use a library like this one to add the functionality.
That said, your problem can be solved by keeping track of which keys are valid, instead of implementing a try-and-see approach.

Error. Unrecognized selector to instance. (Swift)

I've been looking at similar questions, but I still don't understand where I'm going wrong in my situation. Getting this error:
MyAwesomeApp[3481:1330310] -[Session setClient:]: unrecognized selector sent to instance 0x16e05de0
2015-03-15 07:30:29.990 MyAwesomeApp[3481:1330310] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Session setClient:]: unrecognized selector sent to instance 0x16e05de0'
*** First throw call stack:
(0x28e1045f 0x36ca6c8b 0x28e15879 0x28e13797 0x28d45008 0x646c4 0x628b4 0x62ba4 0x2c35de7f 0x2c4c1b35 0x2c35de7f 0x2c35de21 0x2c348c43 0x2c35d88d 0x2c35d567 0x2c356e31 0x2c32d759 0x2c5a12f9 0x2c32c1a9 0x28dd6fbf 0x28dd63cf 0x28dd4a35 0x28d223b1 0x28d221c3 0x3034f201 0x2c38c43d 0xa7a24 0xa7a60 0x37232aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
When I execute this code:
#IBAction func saveButton(sender: AnyObject) {
if session != nil {
editSession()
} else {
createSession()
}
navigationController?.popViewControllerAnimated(true)
}
func editSession() {
session?.sessionTitle = sessionTitleTxt.text
managedObjectContext?.save(nil)
}
func createSession() {
let entityDescription = NSEntityDescription.entityForName("Session", inManagedObjectContext: managedObjectContext!)
let newSession = Session(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
if sessionTitleTxt.text == "" {
newSession.sessionTitle = "Untitled Session"
} else {
newSession.sessionTitle = sessionTitleTxt.text
newSession.client = self.client!
}
managedObjectContext?.save(nil)
SessionsTVC?.client = newSession.client
}
Session class is:
import Foundation
import CoreData
#objc(Session)
class Session: NSManagedObject {
#NSManaged var sessionDate: String
#NSManaged var sessionTitle: String
#NSManaged var sessionNotes: String
#NSManaged var sessionExercises: NSSet
#NSManaged var client: Client
}
Can anyone help me out? I was getting a nil for the client variable before because I have several segues that I had confused, but now I'm getting this selector error and not sure how to move forward.
Thanks for any suggestions!
The error you are getting,
MyAwesomeApp[3481:1330310] -[Session setClient:]: unrecognized selector sent to instance 0x16e05de0
2015-03-15 07:30:29.990 MyAwesomeApp[3481:1330310] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Session setClient:]: unrecognized selector sent to instance 0x16e05de0'
happens when a method that is to be executed cannot be found. This can be thrown either because a method does not exist, or it is being called on the wrong object. In your specific case, the method setClientis being called on the Session object, which is being stored at the memory address of 0x16e05de0
Make sure that the setClient method exists and is supposed to be called on that Session object.
Here is a good link to help you with debugging:
http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Hope this helps!!

Resources