Hi! I am trying to do http requests in Kotlin Nati...
# kotlin-native
m
Hi! I am trying to do http requests in Kotlin Native in ios jsing nsurlsession. I want to do it synchronously and so am using semaphores. However, when the callback for dataTaskWithRequest ends, I get a bad access error which according to the debugger, is caused due to garbage collection. Even when I comment out the first three lines of the callback lambda, I keep getting the error. Any help would be appreciated.
Copy code
fun call() : Unit{

    var url = NSURL.alloc()
    url = url?.initWithString("<https://jsonplaceholder.typicode.com/posts/1>")
    var nsrequest = NSMutableURLRequest(url as NSURL)

    nsrequest.HTTPMethod = "GET"

    var this_nsdata : NSData? = null
    var this_nsresponse : NSURLResponse? = null
    var this_nserror : NSError? = null
    var syncer = dispatch_semaphore_create(0)

    var sess = NSURLSession.sharedSession()

    var task = sess.dataTaskWithRequest(nsrequest) { nsdata: NSData?, nsresponse: NSURLResponse?, nserror: NSError? ->
        this_nsdata = nsdata
        this_nsresponse = nsresponse as NSHTTPURLResponse
        this_nserror = nserror


        dispatch_semaphore_signal(syncer)
    }

    task.resume()

    dispatch_semaphore_wait(syncer, DISPATCH_TIME_FOREVER)

    if(this_nserror == null && this_nsdata != null){

        this_nsresponse as NSHTTPURLResponse
        var nsstrobj = NSString.stringWithUTF8String(this_nsdata!!.bytes as CPointer<ByteVar>)
        print(nsstrobj as String)
    }
    else {
        print("whoops")

    }
}
o
t
You need AtomicReference for cross-thread calls
+initRuntimeIfNeeded()
s
is initRuntimeIfNeeded() ever going to go away and be handled by the compiler?
@thevery Why does the AtomicReference need to be used? If the write access is definitively atomic from the semaphore, is the AtomicReference necessary?
t
iOS semaphore is not the same as java semaphore - you don't have memory model guarantees in KN
{ nsdata: NSData?, nsresponse: NSURLResponse?, nserror: NSError? ->
lambda is invoked in bg thread -> thread crossing triggers immutability violation
As for
initRuntimeIfNeeded
, @olonho should know better than me 😃
And for string conversion use
val body = data?.let { NSString.create(it, NSUTF8StringEncoding) as? String } ?: ""
o
initRuntimeIfNeeded
will go away eventually