realm migration, cannot add property - swift

testing realm, cannot add a new property to my testing class. Followed documentation and some answer here but both are not working. In my code even the "plain" empty default block for migration is not working, using updated realm.
getting this error
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:
- Property 'ComicType.creationDate' has been added." UserInfo={NSLocalizedDescription=Migration is required due to the following errors:
- Property 'ComicType.creationDate' has been added., Error Code=10}
it seems I'm not changing the schemaVersion, but I did in the "basic" migration block. I check the schema version in app delegate with:
let configCheck = Realm.Configuration();
do {
let fileUrlIs = try schemaVersionAtURL(configCheck.fileURL!)
print("schema version \(fileUrlIs)")
} catch {
print(error)
}
my AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
}
})
Realm.Configuration.defaultConfiguration = config
_ = try! Realm()
return true
}
my class:
import Foundation
import RealmSwift
class ComicType: Object {
#objc dynamic var name : String = ""
#objc dynamic var creationDate : Date? //the new property
}

Issue solved this way: the real issue is not about schema number, but about not calling at all the migration code, I realized the migration schema remained always the same. True error is calling let realm = try! Realm() in my view controller using it as global constant. Now using lazy var realm = try! Realm() Great help found here . Now after each change in my model, I update in appDelegate the schemaVersion.

What worked for was to remove the app from the iOS Simulator, and then run it again using XCode. More about this is found here: https://github.com/RocketChat/Rocket.Chat.iOS/issues/104
I was facing a similar issue, my error stack trace was beginning like this:
`fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:
The errors shown was just confirming the some objects have been saved locally. so, there was no clue on what caused the problem.
What I figured was, the issue was that the schema of Realm Database was violated, since I updated the Objects' classes that I have been saving locally. So, it requested that I update the schema.
I suppose that a new Realm file with is created when the app is removed and run again. If so, then a new schema is created that works with latest code

Related

Why can't my app find Firebase Functions?

I can't figure out why I keep getting the Swift warning: Use of unresolved identifier 'Functions on this line of my code: let functions = Functions.functions()
My imports for the viewController includes import Firebase and it works fine when I declare let db = Firestore.firestore() right above the line let functions = Functions.functions()
My podfile includes pod 'Firebase/Functions' and I've installed the pod.
I'm calling functions later using the following code and when I type "functions" it recommends adding .httpsCallable which leads me to believe that it actually does recognize the object "functions":
func getData(){
functions.httpsCallable("helloWorld").call(userData) { (result, error) in
if let error = error {
print(error)
}
if let data = result?.data {
print(data)
}
}
}
Figured it out. Importing Firebase is not enough, one must also import FirebaseFunctions (despite what Swift thinks, see screenshot below).

IBM Watson Visual Recognition API Key fail - Xcode Swift

I'm trying to connect to Watson using VisualRecognitionV3.framework.
The framework's compiled fine (via Carthage), and I think I've got the Service Credentials configured correctly, but when I compile Xcode to the simulator I get an invalid-api-key error.
Has anyone experienced the same issues?
What am I doing wrong?
private let apiKey = "Xn5DUtQU8WzgFTL9qNEFwBjxxxxxxxxxxxxxxxxxx"
private let classifierId = "DefaultCustomModel_2051029379"
private let version = "2018-07-01"
var visualRecognition: VisualRecognition!
override func viewDidLoad() {
super.viewDidLoad()
self.visualRecognition = VisualRecognition(apiKey: apiKey, version: version)
}
override func viewDidAppear(_ animated: Bool) {
let localModels = try? visualRecognition.listLocalModels()
if let models = localModels, models.contains(self.classifierId) {
print("local model found")
} else {
self.updateModel()
}
}
Xcode Error:
Error Domain=com.ibm.watson.developer-cloud.VisualRecognitionV3 Code=403 "ERROR: invalid-api-key" UserInfo={NSLocalizedDescription=ERROR: invalid-api-key}
Watson configuration screenshot:
Watson Config
You need to initialize your VisualRecognition using another initializer, like the following
let visualRecognition = VisualRecognition(version: version, apiKey: apiKey, iamUrl: nil)
The difference is that you will need to call this 3 argument-ed constructor with the third argument, i.e. the iamUrl, even though you make it nil and anything else is the same. This tells the VisualRecognition class to authenticate your app using the IAM.
The git documentation is very confusing, which says in here https://github.com/watson-developer-cloud/swift-sdk#visual-recognition
Note: a different initializer is used for authentication with instances created before May 23, 2018:
Which means the old way should just work, UNLESS, they made a mistake and they actually mean AFTER May 23, 2018
Anyways, if you try it should just work. I was having this issue 30 mins before writing this answer.

Xcode project keeps crashing after converting to Swift 4, "Class implemented in both..."

I recently converted an Xcode project to Swift 4. I fixed all the syntax errors. However, my app now crashes, after outputting an error message which starts
Class MPExportableArtworkProperties is implemented in both...
I have been looking around S/O but all I find is that its related to MapBox which I don't even have in my project/podfile. Can it have something to do with the regular map-kit? It crashes the app when I open the tab with my map, so I'm guessing that's where the problem is.
Full error message, formatted for readability:
objc[24634]: Class MPExportableArtworkProperties is implemented in both
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/MediaPlaybackCore.framework/MediaPlaybackCore
(0x126b1b108) and
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/MediaPlayer.framework/MediaPlayer
(0x1258107d0).
One of the two will be used. Which one is undefined.
This is the plowerthingscontroller saying that you are logged in
libc++abi.dylib: terminating with uncaught exception of type
NSException
I had this exact error, and in the end found it was due to something completely different: a circular dependency. Consider:
class DependencyManager {
static let shared = DependencyManager()
let aDependency: SomeDependency
init() {
aDependency = SomeDependency()
}
func resolve() -> SomeProtocol {
// Create the actual class
return 0
}
}
where SomeDependency requires SomeProtocol
class SomeDependency {
let x: SomeProtocol
// Me trying to be clever and auto-inject the dependency
init(x: SomeProtocol = DependencyManager.shared.resolve()) {
self.x = x
}
}
So when you first access DependencyManager.shared it tries instantiate SomeDependency, which requires DependencyManager.shared to already be instantiated.
I have no idea why MPExportableArtworkProperties is mentioned in the error, however cleaning up the code fixed the issue for me.

Swift Privileged Helper (XPC Listener) Crashing with Illegal Instruction Error

I’ve created a Swift macOS app which uses SMJobBless to create a helper with escalated privileges. This works fine—the helper gets installed to /Library/Privileged Helper Tools and an accompanying LaunchDaemon gets created in /Library/LaunchDaemons. However, the helper is unable to start successfully. Instead, it crashes with an “Illegal instruction: 4” message.
I’ve prepared the helper to respond to XML connections by implementing the NSXPCListenerDelegate protocol. Here‘s my Helper main.swift code:
import Foundation
class HelperDelegate: NSObject, NSXPCListenerDelegate {
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
newConnection.exportedInterface = NSXPCInterface(with: HelperToolProtocol.self)
newConnection.exportedObject = HelperTool()
newConnection.resume()
return true
}
}
let delegate = HelperDelegate()
let listener = NSXPCListener.service()
listener.delegate = delegate
listener.resume()
The crash occurs on the last line, listener.resume().
I tried to launch the helper app manually from the command line (which is identical to what the LaunchDaemon does) and, again, it crashes with the above error message printed to stdout. I don’t have any more ideas on how to test this for the root cause. My implementation is more than rudimentary, following Apple’s guidlines for implementing XM services. Also, the various posts on SO regarding XML services haven’t helped me in resolving this issue. Has anyone of you tried to create a privileged helper in Swift successfully? BTW, the app is not sandboxed.
For the sake of completeness, here’s the code for the HelperTool class referenced in my HelperDelegate class above:
import Foundation
class HelperTool: NSObject, HelperToolProtocol {
func getVersion(withReply reply: (NSData?) -> ()) {
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString" as String) as? String ?? "<unknown version>"
let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ?? "<unknown build>"
if let d = "v\(version) (\(build))".data(using: .utf8, allowLossyConversion: false) {
reply(d as NSData)
}
}
}
And finally the HelperToolProtocol:
import Foundation
#objc(HelperToolProtocol) protocol HelperToolProtocol {
func getVersion(withReply: (NSData?) -> ())
}
Thanks for any help!
After days of testing I finally found a solution which makes my XPC helper launch correctly and respond to any messages. The problem lies in the last three lines of the main.swift module which currently read
let listener = NSXPCListener.service()
listener.delegate = delegate
listener.resume()
which, as put in the question, make the helper crash immediately upon the very last line.
I took these lines directly from Apple’s Creating XPC Services documentation. Here’s the documentation for the NSXPCListener resume() function:
If called on the service() object, this method never returns. Therefore, you should call it as the last step inside the XPC service's main function after setting up any desired initial state and configuring the listener itself.
The solution is to not call the NSXPCListener.service() singleton object but rather instantiate a new NSXPCListener object using the init(machServiceName:)initializer passing the same Mach service name that is being used on the main app’s XPC connection. As resume() in this case would resume immediately—thus terminating the helper—you have to put it on the current run loop to have it run indeterminately. Here’s the new, working code:
let listener = NSXPCListener(machServiceName: "Privilege-Escalation-Sample.Helper")
listener.delegate = delegate
listener.resume()
RunLoop.current.run()

Realm Swift crashing with uncaught exception when trying to get object

I am using RealmSwift in my MacOS/OSX application on OSX 10.12.3 and Realm crashes with uncaught exception when I try to get an object from the database.
Here's the code snippet that crashes on the get object func:
private var database: Realm!
init(some_var: String) {
var configuration = Realm.Configuration()
configuration.fileURL = configuration.fileURL!.deletingLastPathComponent().appendingPathComponent("\(some_var).realm")
do {
debugPrint("Inside init: Current thread \(Thread.current)")
self.database = try Realm(configuration: configuration)
} catch {
debugPrint("realmInit: Can't create realm database.")
}
}
func getObject<T: Object, K>(with primaryKey: K) -> T? {
debugPrint("Inside getObject: Current thread \(Thread.current)")
return self.database.object(ofType: T.self, forPrimaryKey: primaryKey) // THIS LINE THROWS EXCEPTION
}
I get a crash with an uncaught exception:
"Inside init: Current thread <NSThread: 0x600000075700>{number = 5, name = (null)}"
"Inside getObject: Current thread <NSThread: 0x600000075700>{number = 5, name = (null)}"
libc++abi.dylib: terminating with uncaught exception of type NSException
At first I thought it was a threading issue, but you can see that I init the Realm and getObject on the same thread.
Any help would be appreciated please?
Turns out the issue was with the return type being an optional generic.
After a conversation with one of the contributors to the Realm library on github, it sounded like it could potentially be a RealmSwift bug.
Issue has been raised here https://github.com/realm/realm-cocoa/issues/4951
Workaround is to implement a function that returns a Bool if the object exists, and then return a non-optional generic when it does, while create a new object if it doesn't exist.