UserDefault and SharedPreference in Kotlin Multiplatform Mobile (KMM)

expect class SPref

expect fun SPref.getInt(key: String) : Int
expect fun SPref.setInt(key: String, value: Int)
import android.app.Activity
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences

actual typealias SPref = Activity

actual fun SPref.getInt(key: String ) : Int{
val prefs: SharedPreferences = this.getSharedPreferences("", MODE_PRIVATE)
return prefs.getInt(key, -1)
}


actual fun SPref.setInt(key: String, value: Int) {
val prefs: SharedPreferences = this.getSharedPreferences("", MODE_PRIVATE)
val editor = prefs.edit()
editor.putInt(key,value)
editor.apply()
}
import platform.Foundation.NSUserDefaults
import platform.darwin.NSObject

actual typealias SPref = NSObject

actual fun SPref.getInt(key: String) : Int {
return NSUserDefaults.standardUserDefaults.integerForKey(key).toInt()
}

actual fun SPref.setInt(key: String, value : Int){
NSUserDefaults.standardUserDefaults.setInteger(value.toLong(),key)
}
class KMMStorage(val context: SPref) {

fun getInt(key: String): Int {
return context.getInt(key)
}

fun putInt(key: String, value: Int) {
context.setInt(key,value)
}
}
class MainActivity : AppCompatActivity() {

lateinit var tv : TextView

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

tv = findViewById(R.id.text_view)
loadFromSP(tv)
}

fun loadFromSP(view : View) {
var kmmStorage = KMMStorage(this)
var count = kmmStorage.getInt("count")
count++
tv.text = "Current Count is "+count
kmmStorage.putInt("count", count)
}

}
import SwiftUI
import Foundation
import shared

func getCount() -> Int32 {
let kmmStorage = KMMStorage(context : NSObject())
var count = kmmStorage.getInt(key : "count")
count+=1
kmmStorage.putInt(key: "count", value: count)
return count
}

struct ContentView: View {
@State var counter: Int32 = 0
var body: some View {
VStack(spacing: 50) {
Text(String(counter))
Button(action: {
counter = getCount()
}) {
Text("Get Data from User Default")
}
}
}

}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store