[英]Sharing data between an notification service extension and main app
在我的方案中,我在父iOS應用程序和通知服務擴展之間共享數據。 我正在使用Xcode 10.2.1,iOS部署目標10.0
我們已經嘗試了NSUserDefaults和Keychain組,它按預期工作。 將通知服務擴展(TargetB)中的值(存儲模型或數據類型)保存到MainApp(TargetA)的任何其他方法。
一旦應用程序處於終止狀態,我們便將值附加到了模型中,並將其保存在鑰匙串中。
要保存到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")
對於USerDefault:
var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
當應用程序處於非活動狀態時,我想將數據從目標B傳輸到目標A。 另一個要傳輸或保存數據? 請幫我?
在VC中添加以下屬性。
var typeArray = [DataModelType]()
let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.ABC.app")?.appendingPathComponent("type.plist")
您要共享的數據模型
struct DataModelType: Codable {
//define properties which you wanna use.
}
向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
}
}
在擴展名中,無論您要訪問數據的位置,添加以下代碼。
let viewController = ViewController()
let currentDataModel = viewController.fetchDataModel()
也許我沒有正確回答問題。
您可以通過CoreData在應用之間共享數據:
在這里解釋。
通常,您需要將擴展程序和主應用程序添加到一個組中,並在擴展程序的目標中添加xcdatamodeled文件。
我認為UserDefaults,Keychain,CoreData,iCloud以及從其他應用程序那里將數據存儲到您的后端就是您擁有的所有選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.