微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

iOS Widget 不会在主屏幕中第一次读取 UserDeafults 值

如何解决iOS Widget 不会在主屏幕中第一次读取 UserDeafults 值

我使用 UserDefaults 的值设置了我的 WidgetView。 为了在小部件和核心应用之间共享数据,我已经设置了 appGroup。

let appGroupId = "group.com.myAppGroupId"
Text(UserDefaults(suiteName: appGroupId)!.object(forKey: "githubId") as? String ?? "??")

它在预览中显示得很好,但是当我将它添加到主屏幕时,它无法读取属性。并且在相同条件下,当我重建应用程序(cmd+r)时,主屏幕中的小部件很好地读取了 UserDefaults 的值。

我猜不出原因。

++++++ 添加更多代码

实际上,我使用属性包装器将我的 githubId 定义为 UserDefaults。

extension UserDefaults {
    enum Key: String {
        case githubId
    }
  
    static let shared: UserDefaults = {
        let appGroupId = "group.com.myAppGroupId"
        return UserDefaults(suiteName: appGroupId)!
    }()

    @UserDefault(key: .githubId)
    static var githubId: String?
}

我的属性包装器看起来像这样。

@propertyWrapper
struct UserDefault<Value> {
    let key: String
    let defaultValue: Value
    var container: UserDefaults = .shared
    private let publisher = PassthroughSubject<Value,Never>()
    
    var wrappedValue: Value {
        get {
            return container.object(forKey: key) as? Value ?? defaultValue
        }
        set {
            if let optional = newValue as? AnyOptional,optional.isNil {
                container.removeObject(forKey: key)
            } else {
                container.set(newValue,forKey: key) //this is where I set my value
            }
            publisher.send(newValue)
        }
    }

    var projectedValue: AnyPublisher<Value,Never> {
        return publisher.erasetoAnyPublisher()
    }
}

extension UserDefault where Value: ExpressibleByNilLiteral {
    init(key: UserDefaults.Key,_ container: UserDefaults = .shared) {
        self.init(key: key.rawValue,defaultValue: nil,container: container)
    }
}

Loginviewmodel 中,我设置了 githubId 值。

class Loginviewmodel: ObservableObject {
    @Published var githubId = UserDefaults.githubId ?? ""
    private var subscriptions = Set<AnyCancellable>()
    
    init() {
        $githubId
            .sink { githubId in
                UserDefaults.githubId = githubId
            }
            .store(in: &subscriptions)
    }
}

最后我在我的应用中使用了这个值,并使用 UserDefaults.githubId

我上面写的代码UserDefaults(suiteName: appGroupId)!.object(forKey: "githubId"))长版的UserDefaults.githubId

解决方法

是否可以选择使用 @AppStorage ? 您的代码可能如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License,Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,software
  distributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container",so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
 <Server port="8081" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor,you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->
    <Connector connectionTimeout="20000"
     port="8080"
     protocol="HTTP/1.1"
     redirectPort="8443"
     />
     <!-- uncomment this to run servlets secure ie. https -->
      <Connector SSLEnabled="true"
       clientAuth="false"
        keystoreFile="/home/foobar/.keystore"
        keystorePass="changeit"
        maxThreads="200"
        port="8443"
        protocol="org.apache.coyote.http11.Http11NioProtocol"
        scheme="https"
        secure="true" 
        sslProtocol="TLS"
        />
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request,and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering,please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
    
            <!-- SingleSignOn valve,share authentication between web applications
                 Documentation at: /docs/config/valve.html -->
            <!--
            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
            -->
    
            <!-- Access log processes all example.
                 Documentation at: /docs/config/valve.html
                 Note: The pattern used is equivalent to using pattern="common" -->
            <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>
    
          <Context docBase="TempClientServlet" path="/TempClientServlet" reloadable="true" source="org.eclipse.jst.jee.server:TempClientServlet"/>
          <Context path="/TempClientServlet/images" docBase="/var/opt/TempClientServletimages" crossContext="true"/>
          <Context docBase="Temp_Service" path="/Temp_Service" reloadable="true" source="org.eclipse.jst.jee.server:Temp_Service"/>
          <Context docBase="Temp_ServiceClient" path="/Temp_ServiceClient" reloadable="true" source="org.eclipse.jst.jee.server:Temp_ServiceClient"/>
      </Host>
    </Engine>
  </Service>
</Server>
,

.sink 在小部件中不起作用。

无论您想在小部件中显示什么,都必须在设置时间线时完成。小部件不会监听更改。

发生变化时,您必须从应用程序重新加载小部件时间线。将每个时间线条目视为屏幕截图。

WidgetCenter.shared.reloadAllTimelines()

重新加载是按计量进行的,因此请确保您有支票并且不要过度重新加载。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。