6

In my scenario, I'm sharing data between the parent iOS app and notification service extension. I'm using Xcode 10.2.1, iOS Deployment Target 10.0

We have tried the NSUserDefaults and Keychain group it's working as expected. Is any other way to save the values(Store Model or datatypes) from notification service extension(TargetB) to MainApp(TargetA).

We have appended the values into the model once the app is in terminated state and save it in the keychain.

For saving to Keycahin:

NotificationAPI.shared.NotificationInstance.append(Notifications(title: messageTitle, message: messageBody,date: Date()))

let notification = NotificationAPI.shared.NotificationInstance

  let value = keychain.set(try! PropertyListEncoder().encode(notification), forKey: "Notification")

For USerDefault :

var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")

I want to transfer the data from Target B to Target A. when the app is in an inactive state? Another to transfer or saving data? Please help me?

Manikandan S
  • 115
  • 3
  • 18

2 Answers2

0

Maybe I didn't get the question correctly.

You can share data between the app through CoreData:

Here it is explained.

In general, you need to add the extension and the main app in a group and to add your xcdatamodeled file in the target of the extension.

I think UserDefaults, Keychain, CoreData, iCloud, and storing data to your backend from where the other app take it is all the options that you have.

m1sh0
  • 2,236
  • 1
  • 16
  • 21
0

Add below property in your VC.

var typeArray = [DataModelType]()
let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.ABC.app")?.appendingPathComponent("type.plist")

DataModel which you want to share

struct DataModelType: Codable {
    //define properties which you wanna use.
}

Add Extention to ViewController

extension ViewController {

    fileprivate func saveData() {
        let encoder = PropertyListEncoder()
        do{
            let dataEncode = try encoder.encode(typeArray)
            try dataEncode.write(to:path!)
        }
        catch{
            print("Error")
        }
    }

    fileprivate func loadData() {
        if let data = try? Data(contentsOf: path!) {
            let decoder = PropertyListDecoder()
            do {
                typeArray = try decoder.decode([DataModelType].self, from: data)
            }
            catch {
                print("Error")
            }
        }
    }

    func fetchDataModel() -> DataModelType {
        loadData()
        return typeArray
    }
}

In your extension add below code wherever you wanna access data.

let viewController = ViewController()
let currentDataModel = viewController.fetchDataModel()
Animesh
  • 497
  • 5
  • 17