RealmSwift 3.0.2 and Swift4 issue - realm

Using RealmSwift-3.0.2, Cocoapods-1.3.1, Swift-4.0.3, iOS-11.2, XCode-9.2
I am trying to create a Realm object (as I always did the last three years).
But since Swift4, something seems off !
I get the following Error-message:
libc++abi.dylib: terminating with uncaught exception of type NSException
Below is my code:
import RealmSwift
var rlm: Realm?
override func viewDidLoad() {
super.viewDidLoad()
// instantiate Realm
self.rlm = try? Realm() // !!!!!!!!!!! Here is where the above error happens...
}
My PodFile looks like this:
project 'MyApp.xcodeproj'
workspace 'MyApp.xcworkspace'
platform :ios, '11.2'
inhibit_all_warnings!
source 'https://github.com/artsy/Specs.git'
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
def shared_pods
pod 'RealmSwift'
end
target 'MyApp' do
shared_pods
end
target 'MyAppTests' do
shared_pods
end
target 'MyAppUITests' do
shared_pods
end
Any help appreciated !!

I found the error:
My Realm object had a wrong primary-key (i.e. type-fault !!)
override static func primaryKey() -> String? {
return "myID" // !!!! Was "mID" :/ :/
}
After correcting the type-fault, it all works again nicely !
(...would be nice if the RealmSwift error message was somehow more explanatory...)

Related

"sbt server is already booting." error when launching sbt from wsl2 ubuntu

I've installed sbt using sdkman on wsl2 ubuntu setup. Currently sbt 1.4.2 is installed. When I try to launch it from the terminal it gives
sbt server is already booting. Create a new server? y/n (default y) if I choose n, nothing happens. If I choose y, then sbt starts. What I want to do is to be able to start sbt without that error message. Because this behaviour breaks metals on visual studio code.
I checked the sbt source code and found that the method below prints the error message - in sbt/main/src/main/scala/sbt/Main.scala
private def getSocketOrExit(
configuration: xsbti.AppConfiguration
): (Option[BootServerSocket], Option[Exit]) =
try (Some(new BootServerSocket(configuration)) -> None)
catch {
case _: ServerAlreadyBootingException
if System.console != null && !ITerminal.startedByRemoteClient =>
println("sbt server is already booting. Create a new server? y/n (default y)")
val exit = ITerminal.get.withRawInput(System.in.read) match {
case 110 => Some(Exit(1))
case _ => None
}
(None, exit)
case _: ServerAlreadyBootingException =>
if (SysProp.forceServerStart) (None, None)
else (None, Some(Exit(2)))
}
}
So, calling new BootServerSocket(configuration) throws an exception. Exception source is the method below from BootServerSocket.java;
static ServerSocket newSocket(final String sock) throws ServerAlreadyBootingException {
ServerSocket socket = null;
String name = socketName(sock);
try {
if (!isWindows) Files.deleteIfExists(Paths.get(sock));
socket =
isWindows
? new Win32NamedPipeServerSocket(name, false, Win32SecurityLevel.OWNER_DACL)
: new UnixDomainServerSocket(name);
return socket;
} catch (final IOException e) {
throw new ServerAlreadyBootingException();
}
}
I checked the isWindows method and it returns false. So the new UnixDomainServerSocket(name) part is running. And somehow it can't create a unix domain server socket. That's all I found out. Is there a way to fix this? Or is this a bug?
After moving my project files to a directory within wsl2, problem is solved. My project files were in a Windows directory before.

How do I update Xcode codes I can use iOS 14 functions?

I was watching a tutorial on how to fetch user location in swift and I had a problem here:
class teste: CLLocationManager, CLLocationManagerDelegate{
#Published var lctionManager = CLLocationManager()
func locationManagerDidChangeAuthorization (_ manager: CLLocationManagerDelegate){
switch manager.authorizationStatus {
case .authorizedWhenInUse:
print("authorized")
case .denied:
print("denied")
default:
print("unkown")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
print(error.localizedDescription)
}
}
The error was a in locationManagerDiChangeAuthorization (Instance method 'locationManagerDidChangeAuthorization' nearly matches optional requirement 'locationManagerDidChangeAuthorizantion' of protocol 'locationManagerDelegate') and in manager.authorizationStatus( Value of type 'CLLocationManagerDelegate' has no member 'authoizationStatus')
After some research, I found out that these are iOS 14 only, and my code may be written in iOS13 (actually, for some codes, I have to add #available(iOS 14.0, *) to make them work, but this time it didnt seem it work).
But, as a beginner, I don't know how to update my code (searched for some stuff but nothing caught my eyes). How do I update my code? Would it interfere in anything? Is it necessary or its better to write something to integrate both iOS 14 and 13?
Project -> Info -> iOS Deployment Target
here you can change deployment target to iOS 14.

How to Fetch a JSON file in Webassembly

I'm currently experimenting with Webassembly, and one thing I'm trying to do here is with a Webassembly to Fetch data from a JSON file, compile that into a .wasm module, and use that module in Javascript to read the result of the fetch.
I've tried following the code on https://kripken.github.io/emscripten-site/docs/api_reference/fetch.html but the resulting .wasm code is confusing to me because I can't find how to properly load that .wasm module in Javascript.
In case I'm going about this the wrong way, I really need some help with this.
started with this fetch.c file that is supposed to fetch JSON data from a file.
#include <stdio.h>
#include <string.h>
#include <emscripten/fetch.h>
/*////////////////////////
// This file contains the code for fetching
// -> Compiled to .wasm file with emscripten <-
*////////////////////////
void downloadSucceeded(emscripten_fetch_t *fetch) {
printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
// The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1];
emscripten_fetch_close(fetch); // Free data associated with the fetch.
}
void downloadFailed(emscripten_fetch_t *fetch) {
printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status);
emscripten_fetch_close(fetch); // Also free data on failure.
}
int main() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_PERSIST_FILE;
attr.onsuccess = downloadSucceeded;
attr.onerror = downloadFailed;
emscripten_fetch(&attr, "./json/bol_list1.json");
}
I compiled this with : emcc wasm/fetch.c -Os -s WASM=1 -s FETCH=1 -s SIDE_MODULE=1 -s BINARYEN_ASYNC_COMPILATION=0 -o wasm/fetch.wasm
fetch.wasm: https://pastebin.com/cHYpgazy
So, now with that module I'm supposed to read it in Javascript and get the result, but this is where I'm stuck, because as opposed to other examples this .wasm module doesn't have an obvious export/import thing and my previous methods of trying to load it failed.
wasmbyfile.js:
Method 1:
let obj;
loadWebAssembly('./wasm/fetch.wasm') //Testing function
.then(instance => {
obj = instance.exports._main;
console.log(obj);
});
function loadWebAssembly(fileName) {
return fetch(fileName)
.then(response => response.arrayBuffer())
.then(bits => WebAssembly.compile(bits))
.then(module => { return new WebAssembly.Instance(module) });
};
error result: wasmbyfile.js:64 Uncaught (in promise) TypeError: WebAssembly Instantiation: Imports argument must be present and must be an object
at fetch.then.then.then.module (wasmbyfile.js:64)
Method 2:
(async () => {
const fetchPromise = fetch('./wasm/fetch.wasm');
const { instance } = await WebAssembly.instantiateStreaming(fetchPromise);
const result = instance.exports._main;
console.log(result);
})();
error result: Uncaught (in promise) TypeError: WebAssembly Instantiation: Imports argument must be present and must be an object
So I'm stuck at this point, and not really sure how to load the module correctly in JS. I need some help for this, or am I doing this the wrong way from the beginning and is there a better way for me to do this?
You are getting an error because your WASM has import statements, while your call to instantiateStreaming does not send an importObject.
But the basic way to use WASM from Javascript is much simpler than: Just define a function in WASM that you can call from JS, and then you do the "fetch" from JS, for instance ("add.wasm"):
(module
(type $t0 (func (param i32 i32) (result i32)))
(func $add (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
get_local $p0
get_local $p1
i32.add)
(export "add" (func $add)))
And then call it from Javascript:
const wasmInstanceFromFile = await WebAssembly.instantiateStreaming(await fetch('add.wasm'));
let sum = wasmInstanceFromFile.instance.exports.add(1,2);

Problems with HttpBuilder-NG basic authentication for a step definition

I am having problems implementing HttpBuilder-NG basic authentication for a Cucumber feature step definition using Gradle, Groovy and Junit. I have sucessfully implemented this step definition using Behat/PHP. I have also verified the test using Postman.
Here is the build.gradle file
apply plugin: 'groovy'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.12'
compile 'io.github.http-builder-ng:http-builder-ng-core:1.0.2'
testCompile 'junit:junit:4.12'
testCompile 'info.cukes:cucumber-groovy:1.2.5'
testCompile 'info.cukes:cucumber-junit:1.2.5'
}
The github API /user/repos path requires authentication to retrieve the user's repository information but the Get is returning an unAuthorized exception. If I leave out the path I get success but the base URL does not require authentication. Here is the Groovy code:
import static cucumber.api.groovy.EN.*
import cucumber.api.PendingException
import static groovyx.net.http.HttpBuilder.configure
import static groovyx.net.http.util.SslUtils.ignoreSslIssues
Given(~/^I am an authenticated user$/) { ->
def github = configure {
ignoreSslIssues execution
request.uri = 'https://api.github.com'
request.auth.basic('githubUser', 'githubPassword', false)
}.get {
request.uri.path = '/user/repos'
}
assert github != null
println github.dump()
}
And here is the exception I am getting (401):
groovyx.net.http.HttpException: Unauthorized
at groovyx.net.http.NativeHandlers.failure(NativeHandlers.java:69)
at groovyx.net.http.HttpConfigs$BaseHttpConfig$$Lambda$9/15235276.apply(Unknown Source)
at groovyx.net.http.HttpBuilder$ResponseHandlerFunction.apply(HttpBuilder.java:2305)
at groovyx.net.http.JavaHttpBuilder$Action.lambda$execute$2(JavaHttpBuilder.java:168)
at groovyx.net.http.JavaHttpBuilder$Action$$Lambda$56/33475769.call(Unknown Source)
at groovyx.net.http.JavaHttpBuilder$ThreadLocalAuth.with(JavaHttpBuilder.java:331)
at groovyx.net.http.JavaHttpBuilder$Action.execute(JavaHttpBuilder.java:122)
at groovyx.net.http.JavaHttpBuilder.createAndExecute(JavaHttpBuilder.java:374)
at groovyx.net.http.JavaHttpBuilder.doGet(JavaHttpBuilder.java:381)
at groovyx.net.http.HttpBuilder$$Lambda$25/32560218.apply(Unknown Source)
at groovyx.net.http.HttpObjectConfigImpl.nullInterceptor(HttpObjectConfigImpl.java:47)
at groovyx.net.http.HttpObjectConfigImpl$Exec$$Lambda$23/7279823.apply(Unknown Source)
at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:346)
Gradle Test Executor 191 finished executing tests.
at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:1297)
at groovyx.net.http.HttpBuilder$get$0.call(Unknown Source)
at repo-create_steps$_run_closure1.doCall(repo-create_steps.groovy:7)
at ?.Given I am an authenticated user(repo-create.feature:3)
It looks like GitHub does provide BASIC support (https://developer.github.com/v3/auth/) but it is non-standard and they suggest creating the Authorization header yourself, which would look something like this:
#Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.2')
import static groovyx.net.http.HttpBuilder.configure
import static groovyx.net.http.util.SslUtils.ignoreSslIssues
def username = 'blah'
def password = 'blah'
def creds = "$username:$password".bytes.encodeBase64()
def github = configure {
ignoreSslIssues execution
request.uri = 'https://api.github.com'
request.headers['Authorization'] = "Basic $creds"
}.get {
request.uri.path = '/user/repos'
response.failure { fs, obj->
println "Status: ${fs.statusCode}"
fs.headers.each { h->
println h
}
}
}
println github.dump()
However, this presents a problem which you may not have on your end. I have 2-factor authentication enabled on my account so I get the X-GitHub-OTP: required; :2fa-type header back (per the documentation linked above). If you do not have 2-factor you should have what you need.
I added the failure handler to get some additional information about the failure cases - it's not required for the solution.

writeCopyToPath Realm Doesn't work

I try to follow "Bundling a Realm with an App" Documentation.I've try to use method Realm().writeCopyToPath(_:encryptionKey:)) but the problem is i can't make a file on a specific location on my OSX. It's show error that file already exits. Please give me a correct way to use writeCopyToPath
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!, error: nil)
// Create a standalone object
var mydog = Dog()
// Set & read properties
mydog.name = "Rex"
mydog.age = 9
println("Name of dog: \(mydog.name)")
// Realms are used to group data together
let realm = Realm() // Create realm pointing to default file
println(realm.writeCopyToPath("/Users/taforyou/CU-TEP",encryptionKey: nil))
// Save your object
realm.beginWrite()
realm.add(mydog)
realm.commitWrite()
return true
}
}
Output Log When running
Name of dog: Rex
Optional(Error Domain=io.realm Code=4 "open() failed: File exists" UserInfo=0x7fbc704a8cd0 {NSLocalizedDescription=open() failed: File exists, Error Code=4})
Thank you
realm 0.95
The error message getting printed says it all: the file you're trying to create (/Users/taforyou/CU-TEP) already exists. Note that the path that writeCopyToPath is expecting is a full path to the resulting realm file (/path/to/file.realm, not /path/to) just in case CU-TEP is actually a directory.

Resources