构建失败:可选类型“[SFUserAccount] 的值?”没有打开

Build Failed: Value of optional type '[SFUserAccount]?' not unwrapped

本机 swift 开发的新手! 在 https://github.com/forcedotcom/SalesforceMobileSDK-iOS/issues/2072

中打开了以下问题

使用的移动 SDK 版本:5.1.0
在本机应用程序或混合应用程序中发现的问题:本机应用程序
OS版本:10.12.5
设备:iPhone 6

重现步骤:

  1. forceios 创建
  2. 提供的申请类型为 native_swift 并添加其他要求的详细信息
  3. 打开 Xcode
  4. 中的 *.xcworkspace 文件
  5. 构建项目

错误:Value id optional type '[SFUserAccount]?' not unwrapped;

    func handleSdkManagerLogout()
        {
            self.log(.debug, msg: "SFAuthenticationManager logged out.  Resetting app.")
            self.resetViewState { () -> () in
                self.initializeAppViewState()

                // Multi-user pattern:
                // - If there are two or more existing accounts after logout, let the user choose the account
                //   to switch to.
                // - If there is one existing account, automatically switch to that account.
                // - If there are no further authenticated accounts, present the login screen.
                //
                // Alternatively, you could just go straight to re-initializing your app state, if you know
                // your app does not support multiple accounts.  The logic below will work either way.

                var numberOfAccounts : Int;
                let allAccounts = SFUserAccountManager.sharedInstance().allUserAccounts()
                numberOfAccounts = (allAccounts!.count);

                if numberOfAccounts > 1 {
                    let userSwitchVc = SFDefaultUserManagementViewController(completionBlock: {
                        action in
                        self.window!.rootViewController!.dismiss(animated:true, completion: nil)
                    })
                    if let actualRootViewController = self.window!.rootViewController {
                        actualRootViewController.present(userSwitchVc!, animated: true, completion: nil)
                    }
                } else {
                    if (numberOfAccounts == 1) {
                        SFUserAccountManager.sharedInstance().currentUser = allAccounts[0]

// ERROR: Value id optional type '[SFUserAccount]?' not unwrapped;
                    }
                    SalesforceSDKManager.shared().launch()
                }
            }
        }

您需要解包 allAccounts,因为它是一个可选数组。并且由于上面已经使用强制展开来获得numberOfAccounts,因此使用它可能是安全的。

试试这个:

SFUserAccountManager.sharedInstance().currentuser = allAccounts![0]

SFUserAccountManagerallUserAccounts属性是nullable

- (nullable NSArray <SFUserAccount *> *) allUserAccounts;

https://github.com/forcedotcom/SalesforceMobileSDK-iOS/blob/master/libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Security/SFUserAccountManager.h#L188

如果您在尝试使用它时确实知道它会存在,则可以通过键入 allAccounts![0] 执行强制解包。如果您需要处理它可能为零的情况,您需要通过执行以下操作来检查它:

if let accounts = allAccounts
{
   currentUser = accounts[0]
}
else
{
   // does not exist
}

我不能告诉你的是它为 nil 是否真的是你需要处理的有效案例,因为我不熟悉这个库。你需要做研究或自己问他们。