使用 PowerApps 开发可脱机运行的应用Develop offline-capable apps with PowerApps

作为移动应用开发者,最常遇到的情境之一是,让用户能够在联网受限或根本无法联网的情况下高效工作。One of the most common scenarios you face as a mobile app developer is enabling your users to be productive when there is limited connectivity or no connectivity at all. PowerApps 提供了一系列功能和行为,有助于开发可脱机运行的应用。PowerApps has a set of features and behaviors that help you to develop offline-capable apps. 你可以:You can:

  • 在脱机时启动 PowerApps 移动应用。Launch the PowerApps mobile app when offline.
  • 在脱机时运行你开发的应用。Run apps you develop when offline.
  • 使用 Connection 信号对象确定应用何时处于脱机、联机或按流量计费的连接状态中。Determine when an app is offline, online, or in a metered connection by using the Connection signal object.
  • 在脱机时使用集合或利用 LoadData 和 SaveData 等函数进行基本数据存储。Use collections and leverage functions such as LoadData and SaveData for basic data storage when offline.

如何生成可脱机运行的应用How to build offline capable apps

在脱机情境中,首先需要考虑的是应用如何处理数据。The first thing to think about in offline scenarios is how your apps work with data. PowerApps 中的应用主要通过平台提供的一组连接器(如 SharePoint、Office 365 和 Common Data Service)访问数据。Apps in PowerApps primarily access data through a set of connectors that the platform provides, such as SharePoint, Office 365, and the Common Data Service. 还可以生成自定义连接器,让应用能够访问任何提供 RESTful 终结点的服务。You can also build custom connectors that enable apps to access any service that provides a RESTful endpoint. 这可以是 Web API 或 Azure Functions 等服务。This could be a Web API or a service such as Azure Functions. 所有这些连接器都通过 Internet 使用 HTTPS。也就是说,用户必须联机,才能访问数据,并使用服务提供的其他任何功能。All these connectors use HTTPS over the Internet, which means your users must be online for them to access data and any other capabilities that a service offers.

使用连接器的 PowerApps 应用

处理脱机数据Handling offline data

PowerApps 最有趣的方面之一是,它提供一系列功能和公式,以便你可以一致地筛选、搜索、排序、聚合和管理数据,无论数据源如何。One of the most interesting aspects of PowerApps is its set of capabilities and formulas that enable you to filter, search, sort, aggregate, and manipulate data in a consistent way regardless of the data source. 数据源包括应用内的内存中集合、SharePoint 列表、SQL 数据库和 Common Data Service。Sources range from in-memory collections in the app, to SharePoint lists, to SQL databases and the Common Data Service. 借助这种一致性,可以轻松地将应用重新定位为使用不同的后端。This consistency enables you to easily retarget an app to use a different backend. 更重要的是,还可以使用本地集合进行数据管理,几乎不用更改应用的逻辑。More importantly here, it also enables you to use local collections for data management with almost no changes to an app's logic. 实际上,本地集合是用于处理脱机数据的主要机制。In fact, local collections are the primary mechanism for handling offline data.

生成脱机 Twitter 应用Building an offline Twitter app

为了突出应用开发的脱机方面,我们将展示简单的 Twitter 方案。To keep the focus on the offline aspects of app development, we'll show you a simple scenario focused around Twitter. 我们将生成一个应用,方便你在脱机时阅读 Twitter 帖子并提交推文。We'll build an app that enables you to read Twitter posts and submit tweets while being offline. 处于联机状态时,此应用会发布推文并重新加载本地数据。When the app comes online, the app posts tweets and reloads the local data.

粗略来看,此应用执行以下操作:At a high level, the app does the following:

  1. 当此应用启动时(以第一屏幕的“OnVisible”属性为依据):On app startup (based on the first screen's OnVisible property):

    • 如果设备处于联机状态,我们会直接访问 Twitter 连接器来提取数据,然后在集合中填充这些数据。If the device is online, we access the Twitter connector directly to fetch data, and populate a collection with that data.
    • 如果设备处于脱机状态,我们会使用 LoadData 从本地缓存文件加载数据。If the device is offline, we load the data from a local cache file using LoadData.
    • 我们允许用户提交推文 - 在联机状态下,我们会将推文直接发布到 Twitter,并刷新本地缓存。We enable the user to submit tweets - if online we post directly to Twitter and refresh the local cache.
  2. 在联机状态下,我们每 5 分钟会执行一次以下操作:Every 5 minutes, if online:

    • 发布我们在本地缓存中存储的所有推文。We post any tweets that we have in the local cache.
    • 刷新本地缓存,并使用 SaveData 进行保存。We refresh the local cache and save it using SaveData.

第 1 步:新建手机应用Step 1: Create a new phone app

  1. 打开 PowerApps Studio。Open PowerApps Studio.
  2. 依次单击或点击“新建” > “空白应用” > “手机布局”。Click or tap New > Blank app > Phone layout.

    空白应用 -> 手机布局

第 2 步:添加 Twitter 连接Step 2: Add a Twitter connection

  1. 依次单击或点击“内容” > “数据源”,然后选择“数据源”面板上的“添加数据源”。Click or tap Content > Data sources, then choose Add data source on the Data sources panel.
  2. 单击或点击“新建连接”,选择“Twitter”,然后单击或点击“创建”。Click or tap New Connection , select Twitter , and click or tap Create.
  3. 输入凭据,然后创建连接。Enter your credentials, and create the connection.

    添加 Twitter 连接

第 3 步:在此应用启动时将推文加载到“LocalTweets”集合中Step 3: Load tweets into a LocalTweets collection on app startup

选择此应用中“Screen1”的“OnVisible”属性,然后复制以下公式:Select the OnVisible property for Screen1 in the app, and copy in the following formula:

If(Connection.Connected,

    ClearCollect(LocalTweets, Twitter.SearchTweet("PowerApps", {maxResults: 100}));

    UpdateContext({statusText: "Online data"})

    ,

    LoadData(LocalTweets, "Tweets", true);

    UpdateContext({statusText: "Local data"})

);

LoadData(LocalTweetsToPost, "LocalTweets", true);

SaveData(LocalTweets, "Tweets")

用于加载推文的公式

此公式会检查设备是否处于联机状态:This formula checks if the device is online:

  • 如果设备处于联机状态,则会将最多 100 篇搜索词为“PowerApps”的推文加载到“LocalTweets”集合中。If the device is online, it loads into a LocalTweets collection up to 100 tweets with the search term "PowerApps".
  • 如果设备处于脱机状态,则会从“Tweets”文件(若有)加载本地缓存。If the device is offline, it loads the local cache from a file called "Tweets," if it's available.
  1. 插入一个高度可调的新库:依次单击或点击“插入” > “库” > “高度可调的空白库”。Insert a new flexible height gallery: Insert > Gallery > Blank flexible height.
  2. 将“Items”属性设置为“LocalTweets”。Set the Items property to LocalTweets.
  3. 添加四个“标签”控件来显示每篇推文的数据,然后将“Text”属性设置为:Add four Label controls to display data from each tweet, and set the Text properties to:
    • ThisItem.TweetTextThisItem.TweetText
    • ThisItem.UserDetails.FullName & " @" & ThisItem.UserDetails.UserNameThisItem.UserDetails.FullName & " @" & ThisItem.UserDetails.UserName
    • "RT: " & ThisItem.RetweetCount"RT: " & ThisItem.RetweetCount
    • Text(DateTimeValue(ThisItem.CreatedAtIso), DateTimeFormat.ShortDateTime)Text(DateTimeValue(ThisItem.CreatedAtIso), DateTimeFormat.ShortDateTime)
  4. 添加一个“图像”控件,然后将“Image”属性设置为“ThisItem.UserDetails.ProfileImageUrl”。Add an Image control, and set the Image property to ThisItem.UserDetails.ProfileImageUrl.

第 5 步:添加连接状态标签Step 5: Add a connection status label

插入一个新“标签”控件,然后将“Text”属性设置为以下公式:Insert a new Label control, and set its Text property to the following formula:

If (Connection.Connected, "Connected", "Offline")

此公式检查设备是否处于联机状态。This formula checks if the device is online. 如果处于联机状态,标签文本显示“已连接”;否则,显示“脱机”。If it is, the text of the label is "Connected", otherwise it's "Offline".

第 6 步:添加用于撰写新推文的文本输入控件Step 6: Add a text input to compose new tweets

  1. 插入一个名为“NewTweetTextInput”的新“文本输入”控件。Insert a new Text input control named "NewTweetTextInput".
  2. 将文本输入控件的“Reset”属性设置为“resetNewTweet”。Set the Reset property of the text input to resetNewTweet.

第 7 步:添加用于发布推文的按钮Step 7: Add a button to post the tweet

  1. 添加一个“按钮”控件,然后将“Text”属性设置为“Tweet”。Add a Button control, and set the Text property to "Tweet".
  2. 将“OnSelect”属性设置为以下公式:Set the OnSelect property to the following formula:

    If (Connection.Connected,
    
        Twitter.Tweet("", {tweetText: NewTweetTextInput.Text}),
    
        Collect(LocalTweetsToPost, {tweetText: NewTweetTextInput.Text});
    
        SaveData(LocalTweetsToPost, "LocalTweetsToPost")
    
    );
    
    UpdateContext({resetNewTweet: true});
    
    UpdateContext({resetNewTweet: false})
    

此公式会检查设备是否处于联机状态:This formula checks if the device is online:

  • 如果设备处于联机状态,则会立即发布推文。If the device is online, it tweets the text immediately.
  • 如果设备处于脱机状态,则会将推文捕获到“LocalTweetsToPost”集合中,并将其保存到此应用中。If the device is offline, it captures the tweet in a LocalTweetsToPost collection, and saves it to the app.

然后,此公式会重置文本框中的文本。Then the formula resets the text in the text box.

第 8 步:添加每五分钟检查一次推文的计时器Step 8: Add a timer to check for tweets every five minutes

添加一个新“计时器”控件:Add a new Timer control:

  • 将“Duration”属性设置为“300000”。Set the Duration property to 300000.
  • 将“AutoStart”属性设置为“true”。Set the AutoStart property to true.
  • 将“OnTimerEnd”设置为以下公式:Set the OnTimerEnd to the following formula:

    If(Connection.Connected,
    
        ForAll(LocalTweetsToPost, Twitter.Tweet("", {tweetText: tweetText}));
    
        Clear(LocalTweetsToPost);
    
        Collect(LocalTweetsToPost, {tweetText: NewTweetTextInput.Text});
    
        SaveData(LocalTweetsToPost, "LocalTweetsToPost");
    
        UpdateContext({statusText: "Online data"})
    )
    

此公式检查设备是否处于联机状态。This formula checks if the device is online. 如果处于联机状态,此应用会发布“LocalTweetsToPost”集合中的所有推文。If it is, the app tweets all the items in the LocalTweetsToPost collection. 然后,它会清除集合。Then it clears the collection.

至此,此应用已经创建完,让我们先来预览一下,然后再进行测试。Now that the app is finished, let's check out how it looks before we move on to testing. 左侧的此应用处于联机状态;右侧的此应用处于脱机状态,有一篇待重新联机时发布的推文。On the left, the app is connected; and on the right, it's offline, with one tweet ready to post when it's online again.

生成的应用的联机和脱机模式

测试应用Testing the app

请按照以下步骤操作,测试此应用:Use the following steps to test the app:

  1. 在处于联机状态的移动设备上运行 PowerApps。Run PowerApps on a mobile device while online.

    至少必须在处于联机状态下运行一次应用,才能将应用下载到设备上。You must run an app at least once while being online, so you can download the app to the device.

  2. 启动 Twitter 应用。Launch the Twitter app.
  3. 你会发现,推文已加载,且状态显示为“已连接”。Notice that the tweets are loaded, and that the status shows Connected.
  4. 完全关闭 PowerApps。Close PowerApps completely.
  5. 为了确保设备处于脱机状态,将设备设置为飞行模式。Set the device to airplane mode to ensure that it's offline.
  6. 运行 PowerApps。Run PowerApps.

    现在可以脱机运行 Twitter 应用,并能访问以前联机时在此设备上运行过的其他任何应用(即,PowerApps 会隐藏尚未下载到设备中的所有应用)。You can now run the Twitter app offline, and you have access to any other apps that you have previously run on this device while online (i.e. PowerApps hides any apps that haven't yet been downloaded to your device).

  7. 再次运行此应用。Run the app again.
  8. 你会发现,此应用可以正确反映连接状态,状态显示为“脱机”。Notice how it correctly reflects the connection state, with a status of Offline.
  9. 撰写新推文。Write a new tweet. 它会存储在“LocalTweetsToPost”本地集合中。It will be stored locally in the LocalTweetsToPost collection.
  10. 退出飞行模式。Exit airplane mode. 当计时器触发后,此应用发布这篇推文。After the timer triggers, the app posts the tweet.

我们希望这篇文章能够帮助你了解 PowerApps 提供的用于生成脱机应用的功能。We hope this article gives you an idea of the capabilities that PowerApps has for building offline apps. 和以往一样,请在我们的论坛中提供反馈,并在 PowerApps 社区博客中分享你的脱机应用示例。As always, please provide feedback in our forum and share your examples of offline apps in the PowerApps community blog.