ios 使用应用程序组在应用程序之间通信和持久化数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24015506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Communicating and persisting data between apps with App Groups
提问by streem
iOS 8 revealed a new API yesterday concerning App Groups. It was kind of messy before to share data and communicate between apps and I believe that's precisely what App Groups is intended to correct.
iOS 8 昨天发布了一个关于 App Groups 的新 API。以前在应用程序之间共享数据和通信有点混乱,我相信这正是 App Groups 旨在纠正的。
In my app I have enabled App Groups and added a new group but I just can't find any documentation on how to use it. Documentation and API references only state how to add a group.
在我的应用程序中,我启用了应用程序组并添加了一个新组,但我找不到任何有关如何使用它的文档。文档和 API 参考仅说明如何添加组。
So what is App Groups really intended to do? Is there any documentation somewhere on how to use it?
那么 App Groups 的真正目的是什么?有没有关于如何使用它的文档?
采纳答案by Santa Claus
Another benefit to App Groups is the ability to share a NSUserDefaults
database. This also works for App Extensions (notification center widgets, custom keyboards, etc).
App Groups 的另一个好处是能够共享NSUserDefaults
数据库。这也适用于应用程序扩展(通知中心小部件、自定义键盘等)。
Initialize your NSUserDefaults
object like this in all applications in the app group and they will share the database:
NSUserDefaults
在 app 组中的所有应用程序中像这样初始化您的对象,它们将共享数据库:
Objective-C:
目标-C:
[[NSUserDefaults alloc] initWithSuiteName:@"<group identifier>"];
Swift:
迅速:
NSUserDefaults(suiteName: "<group identifier>")
Keep in mind everything from the [NSUserDefaults standardUserDefaults]
database for each application will not carry over into this database.
请记住[NSUserDefaults standardUserDefaults]
,每个应用程序的数据库中的所有内容都不会转移到此数据库中。
The documentationgives a correct example as well (As of Beta 3).
该文档还提供了一个正确的示例(从 Beta 3 开始)。
And don't forget to synchronize the database:
并且不要忘记同步数据库:
[yourDefaults synchronize];
回答by TenaciousJay
Sharing NSUserDefaults data between multiple apps
在多个应用程序之间共享 NSUserDefaults 数据
In order to have shared defaults between an app and an extension or between 2 apps you have to add an App Group in your settings using the following steps:
为了在应用程序和扩展程序之间或两个应用程序之间共享默认值,您必须使用以下步骤在您的设置中添加一个应用程序组:
- In the Project Navigator click on the *.xcodeproj file (should be at the top).
- To the right of the Project Navigator look for Project and Targets. Under targets click on your primary target (should be the first thing under Targets).
- Towards the top, click on the Capabilities tab.
- In the App Groups section click the switch to the right to turn App Groups ON.
- Click on the + button and add an App Group named group.com.company.myApp.
- Go to the same place in your other apps and this group should now be available to select. Turn this group on for each app that will be using this shared data.
- 在 Project Navigator 中单击 *.xcodeproj 文件(应该在顶部)。
- 在项目导航器的右侧寻找项目和目标。在目标下点击你的主要目标(应该是目标下的第一件事)。
- 在顶部,单击 Capabilities 选项卡。
- 在应用程序组部分中,单击右侧的开关以打开应用程序组。
- 单击 + 按钮并添加一个名为group.com.company.myApp的应用程序组。
- 转到其他应用程序中的同一位置,现在应该可以选择该组。为将使用此共享数据的每个应用程序打开此组。
Note: If you go to the Apple Developer Portal (the Apple website that shows all of your Certificates, Identifiers, Devices and Provisioning Profiles) and go to Identifiers > App Groups you should see this new App Group.
注意:如果您转到 Apple Developer Portal(显示您的所有证书、标识符、设备和配置文件的 Apple 网站)并转到标识符 > 应用程序组,您应该会看到这个新的应用程序组。
To store data:
存储数据:
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")!
userDefaults.setObject("user12345", forKey: "userId")
userDefaults.synchronize()
To retrieve data:
检索数据:
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")
if let testUserId = userDefaults?.objectForKey("userId") as? String {
print("User Id: \(testUserId)")
}
回答by Wayne Hartman
Application groups, according to my interpretation of the existing documentation, are primarily targeted for extensions, more specifically, for widgets. Widgets are their own application bundle that coexist with your app. Since they are a separate application and therefore have their own sandbox, you will need to use App Groups to share files.
根据我对现有文档的解释,应用程序组主要针对扩展,更具体地说,针对小部件。小部件是它们自己的应用程序包,与您的应用程序共存。由于它们是一个单独的应用程序,因此有自己的沙箱,您将需要使用应用程序组来共享文件。
After some header grep'ing, I think I found the API needed, but was actually put in as part of iOS 7.
经过一些标题 grep'ing 之后,我想我找到了需要的 API,但实际上是作为 iOS 7 的一部分放入的。
NSFileManager
has a method on it containerURLForSecurityApplicationGroupIdentifier:
where you can pass in the identifier you created when turning on App Groups for your apps:
NSFileManager
有一个方法containerURLForSecurityApplicationGroupIdentifier:
,您可以在其中传递您在为您的应用程序打开应用程序组时创建的标识符:
NSURL *containerURL = [[NSFileManager defaultManager]
containerURLForSecurityApplicationGroupIdentifier:@"group.com.company.app"];
回答by blackjacx
One important trap I tapped into today is the following:
我今天发现的一个重要陷阱如下:
In many projects I saw a single app target and with different bundle identifiers set for each configuration of that target. Here things get messy. What the developers intended was to create a debug app for the debug config and a production app for the release target.
在许多项目中,我看到了一个应用程序目标,并且为该目标的每个配置设置了不同的包标识符。这里事情变得混乱。开发人员打算为调试配置创建一个调试应用程序,并为发布目标创建一个生产应用程序。
If you do so both apps will share the same NSUserDefaults when they are set up like so
如果你这样做,两个应用程序将在像这样设置时共享相同的 NSUserDefaults
var userDefaults = NSUserDefaults(suiteName: "group.com.company.myApp")
userDefaults!.setObject("user12345", forKey: "userId")
userDefaults!.synchronize()
This causes problems in many places:
这会导致很多地方出现问题:
- Imagine you set YES for a key when a special app-intro-screen has been shown to the user. The other app will now also read YES and don't show the intro.
- Yes some apps also store oAuth tokens in their user defaults. Anyways... Depending on the implementation, the app will recognize that there's a token and start retrieving data using the wrong token. The chance is high that this will fail with strange errors.
- 想象一下,当一个特殊的应用程序介绍屏幕显示给用户时,你为一个键设置了 YES。另一个应用程序现在也将读取 YES 并且不显示介绍。
- 是的,某些应用程序还将 oAuth 令牌存储在其用户默认值中。无论如何......根据实现,应用程序将识别出有一个令牌并开始使用错误的令牌检索数据。这很可能会因奇怪的错误而失败。
The solution to this problem in general is to prefix the defaults keys with the current configuration built. You can detect the configuration easily at runtime by setting different bundle identifiers for your configurations. Then just read the bundle identifier from NSBundle.mainBundle()
. If you have the same bundle identifiers you need to set different preprocessor macros like
解决此问题的一般方法是使用当前构建的配置为默认键添加前缀。通过为配置设置不同的包标识符,您可以在运行时轻松检测配置。然后只需从NSBundle.mainBundle()
. 如果您有相同的包标识符,则需要设置不同的预处理器宏,例如
#ifdef DEBUG
NSString* configuration = @"debug";
#elif RELEASE
NSString* configuration = @"release";
#endif
In Swift it will look almost the same:
在 Swift 中,它看起来几乎一样:
#if DEBUG
let configuration = "debug"
#elseif RELEASE
let configuration = "release"
#endif
回答by Hardik Thakkar
To store
储藏
let shared: NSUserDefaults = NSUserDefaults(suiteName: "group.abcapp")!
shared.setObject("abc.png", forKey: "favEmoji")
shared.synchronize()