天天看點

ios 圖表_如何在iOS中建立即時圖表 如何在iOS中建立即時圖表 (How to build a realtime chart in iOS)

ios 圖表

by Neo Ighodaro

由新Ighodaro

如何在iOS中建立即時圖表 (How to build a realtime chart in iOS)

Nowadays, gathering data is one of the keys to understanding how products are perceived. Gathering some data from users can help you build better products and understand your users. However, all the data in the world would be useless without a way to visualize it.

如今,收集資料是了解産品感覺方式的關鍵之一。 從使用者那裡收集一些資料可以幫助您建構更好的産品并了解您的使用者。 但是,如果沒有一種可視化的方法,世界上所有的資料将毫無用處。

In this article, we will explore how to create a simple realtime chart in iOS. The chart will receive data and update in realtime to the screens of everyone currently logged into your application. We will assume this is a chart that monitors how many visitors are using a website. Let’s begin.

在本文中,我們将探讨如何在iOS中建立簡單的實時圖表。 該圖表将接收資料并實時更新到目前登入到您的應用程式的每個人的螢幕。 我們将假定這是一個圖表,用于監視正在使用網站的通路者人數。 讓我們開始。

For context, here is a sample of what we will be building:

對于上下文,這是我們将要建構的示例:

Please note: A basic understanding of Swift and Node.js is needed to follow this tutorial.

請注意:遵循本教程需要對Swift和Node.js有基本了解。

在iOS中建立即時圖表的需求 (Requirements for building a realtime chart in iOS)

Before we begin this tutorial, you will need to have the following requirements:

在開始本教程之前,您需要滿足以下要求:

  • A MacBook Pro.

    MacBook Pro。

  • Xcode installed on your machine.

    Xcode安裝在您的計算機上。

  • Basic knowledge of Swift and using Xcode.

    Swift和使用Xcode的基本知識。

  • Basic knowledge of JavaScript (Node.js).

    JavaScript的基本知識(Node.js)。

  • Node.js and NPM installed on your machine.

    您的計算機上安裝了Node.js和NPM。

  • Cocoapods **installed on your machine.

    您的機器上安裝了Cocoapods ** 。

  • A Pusher application

    推送器應用程式

When you have all the requirements, then we can begin.

當您擁有所有要求時,我們就可以開始了。

準備在Xcode中建立我們的實時圖表應用程式 (Preparing to create our realtime chart application in Xcode)

Launch Xcode on your Mac and create a new project (call it whatever you want). Follow the new application wizard and create a new Single-page application. Once the project has been created, close Xcode and launch your terminal application.

在Mac上啟動Xcode并建立一個新項目(随心所欲地調用它)。 遵循新的應用程式向導并建立一個新的單頁應用程式 。 建立項目後,關閉Xcode并啟動您的終端應用程式。

In the terminal,

cd

to the root of the application directory. Then run the command

pod init

. This will generate a Podfile. Update the contents of the Podfile to the contents below (replace

PROJECT_NAME

with your project name):

在終端中,

cd

到應用程式目錄的根目錄。 然後運作指令

pod init

。 這将生成一個Podfile 。 将Podfile的内容更新為以下内容(用項目名稱替換

PROJECT_NAME

):

platform :ios, '9.0'target 'PROJECT_NAME' do  use_frameworks!    pod 'Charts', '~> 3.0.2'  pod 'PusherSwift', '~> 4.1.0'  pod 'Alamofire', '~> 4.4.0'end
           

Save the Podfile and then go to your terminal and run the command:

pod install

.

儲存Podfile,然後轉到終端并運作指令:

pod install

Running this command will install all the third-party packages we need to build our realtime iOS chart application.

運作此指令将安裝建構實時iOS圖表應用程式所需的所有第三方軟體包。

The first package it will install is Charts, which is a package for making beautiful charts on iOS. The second package is the Pusher swift SDK. The last package is Alamofire, a package for making HTTP requests on iOS.

它将安裝的第一個軟體包是Charts ,這是用于在iOS上制作漂亮圖表的軟體包。 第二個軟體包是Pusher swift SDK。 最後一個軟體包是Alamofire ,一個用于在iOS上發出HTTP請求的軟體包。

Once the installation is complete, open the

**.xcworkspace**

file in your project directory root. This should launch Xcode. Now we are ready to start creating our iOS application.

安裝完成後,在項目目錄根目錄中打開

**.xcworkspace**

檔案。 這應該啟動Xcode。 現在我們準備開始建立我們的iOS應用程式。

在Xcode中建立我們的實時圖表應用程式視圖 (Creating our realtime chart application views in Xcode)

To begin, we will create the necessary views we need for our realtime chart application. Open the Main.storyboard file and let’s start designing our view.

首先,我們将建立實時圖表應用程式所需的必要視圖。 打開Main.storyboard檔案,讓我們開始設計視圖。

First, create a rectangular view from edge to edge at the top of the View Controller in the storyboard. In that view, add a button and add the title “Simulate Visits”. Next, create another view that is also a rectangle, spanning from the end of the first view above to the bottom of the screen. This view will be where we will render the realtime chart.

首先,在情節提要中的View Controller頂部從邊緣到邊緣建立一個矩形視圖。 在該視圖中,添加一個按鈕并添加标題“模拟通路”。 接下來,建立另一個也是矩形的視圖,從上方的第一個視圖的末端到螢幕的底部。 該視圖将是我們渲染實時圖表的地方。

When you are done creating the views, you should have something like what’s shown in the image below.

完成建立視圖後,您應具有下圖所示的内容。

As it currently stands, the views do nothing. Let us connect some functionality to the iOS chart application view.

從目前的情況來看,視圖什麼也沒做。 讓我們将一些功能連接配接到iOS圖表應用程式視圖。

向我們的iOS圖表應用程式添加基本功能 (Adding basic functionality to our iOS chart application)

As said before, our application’s views and buttons are not connected to our

ViewController

, so let’s fix that.

如前所述,我們的應用程式的視圖和按鈕未連接配接到

ViewController

,是以讓我們對其進行修複。

In Xcode, while the storyboard is still open, click on the “Show the Assistant Editor” button on the top right of the page to split the view into storyboard and code view. Now, click once on the button you created, and while holding

ctrl

, click and drag the link to the code editor. Then create an

@IBaction

as seen in the images below:

在Xcode中,情節提要闆仍處于打開狀态,請單擊頁面右上方的“顯示助手編輯器”按鈕,以将視圖分為情節提要和代碼視圖。 現在,在您建立的按鈕上單擊一次,然後在按住

ctrl

同時單擊并拖動連結到代碼編輯器。 然後建立一個

@IBaction

,如下圖所示:

When the link is complete, you should see something like this added to the code editor:

連結完成後,您應該會在代碼編輯器中看到以下内容:

@IBAction func simulateButtonPressed(_ sender: Any) {}
           

Great! Now that you have created the first link, we will have to create one more link to the chart view.

大! 現在您已經建立了第一個連結,我們将不得不再建立一個指向圖表視圖的連結。

On your storyboard, click the view and on the “Identity Inspection” tab, make sure the view is connected to

LineChartView

as seen below.

在情節提要闆上,單擊視圖,然後在“身份檢查”頁籤上,確定将視圖連接配接到

LineChartView

,如下所示。

Now that the view is connected to a view class, repeat the same as we did before to link the button. Only this time, instead of creating an

@IBAction

, we will create an

@IBOutlet

. Images are shown below:

現在,視圖已連接配接到視圖類,重複與連結按鈕之前相同的操作。 隻是這一次,而不是建立一個

@IBAction

,我們将建立一個

@IBOutlet

。 圖檔如下所示:

When the link is complete, you should see something like this added to the code editor:

連結完成後,您應該會在代碼編輯器中看到以下内容:

@IBOutlet weak var chartView: LineChartView!
           

Finally, at the top of the

ViewController

, import the Charts package. You can add the code below right under

import UIKit

in the

ViewController

.

最後,在

ViewController

的頂部,導入Charts包。 您可以在

ViewController

import UIKit

下的下面添加代碼。

import Charts
           

Now that we have linked both elements to our code, every time the Simulate Visits button is pressed, the simulateButtonPressed function will be called.

現在我們已經将兩個元素都連結到了我們的代碼,每當按下“ 模拟通路”按鈕時,都會調用simulateButtonPressed函數。

向我們的iOS圖表應用程式添加實時功能 (Adding realtime functionality to our iOS chart application)

The final piece of the puzzle will be displaying a chart and making it update in realtime across all devices viewing the chart.

難題的最後一部分将是顯示圖表,并使其在檢視該圖表的所有裝置上實時更新。

To achieve this, we will do the following:

為此,我們将執行以下操作:

  • Create a function that updates our chart depending on the numbers.

    建立一個根據數字更新圖表的函數。

  • Make our request button call the backend, which will in turn send simulated data to Pusher.

    讓我們的請求按鈕調用後端,後端将依次将模拟資料發送到Pusher。

  • Create a function that listens for events from Pusher and, when one is received, it triggers the update chart function we created earlier.

    建立一個偵聽來自Pusher的事件的函數,并在收到一個事件時觸發我們之前建立的更新圖表函數。

建立一個觸發函數來更新我們的圖表 (Create a trigger function to update our chart)

Let’s create the function that updates our chart depending on the numbers supplied to it. Open the

ViewController

, and in it declare a class property right under the class declaration. We will use this property to track the visitors:

讓我們建立一個函數,根據提供給它的數字更新圖表。 打開

ViewController

,并在其中的類聲明下聲明一個類屬性。 我們将使用此屬性來跟蹤訪客:

var visitors: [Double] = []
           

Next, we will add the function that will do the actual update to the chart view:

接下來,我們将向圖表視圖添加執行實際更新的功能:

private func updateChart() {    var chartEntry = [ChartDataEntry]()
           
for i in 0..<visitors.count {        let value = ChartDataEntry(x: Double(i), y: visitors[i])        chartEntry.append(value)    }        let line = LineChartDataSet(values: chartEntry, label: "Visitor")    line.colors = [UIColor.green]
           
let data = LineChartData()    data.addDataSet(line)
           
chartView.data = data    chartView.chartDescription?.text = "Visitors Count"}
           

In the code above, we declare

chartEntry

where we intend to store all our chart data. Then we loop through the available

visitors

and, for each of them, we add a new

ChartDataEntry(x: Double(i), y: visitors[i])

that tells the chart the X and Y positions.

在上面的代碼中,我們聲明

chartEntry

我們打算在其中存儲所有圖表資料。 然後,我們周遊可用的

visitors

并為每個

visitors

添加一個新的

ChartDataEntry(x: Double(i), y: visitors[i])

,以告知圖表X和Y位置。

We set the color the line chart will be displayed in. We create the

LineChartData

and add the

line

which contains our data points. Finally, we add the data to the

chartView

and set the chart view description.

我們設定折線圖将顯示的顔色。我們建立

LineChartData

并添加包含資料點的

line

。 最後,我們将資料添加到

chartView

并設定圖表視圖說明。

讓我們的模拟按鈕稱為端點 (Make our simulate button call an endpoint)

The next thing we need to do is make our request button trigger a backend, which will in turn send simulated data to Pusher.

接下來需要做的是使我們的請求按鈕觸發一個後端,該後端将反過來将模拟資料發送到Pusher。

To do this, we need to update the view controller one more time. In the

ViewController

, import the Alamofire package right under the Charts package:

為此,我們需要再更新一次視圖控制器。 在

ViewController

,直接在Charts包下導入Alamofire包:

import Alamofire
           

Now, replace the

simulateButtonPressed

function with the code below:

現在,用下面的代碼替換

simulateButtonPressed

函數:

@IBAction func simulateButtonPressed(_ sender: Any) {    Alamofire.request("http://localhost:4000/simulate", method: .post).validate().responseJSON { (response) in        switch response.result {        case .success(_):           _ = "Successful"        case .failure(let error):           print(error)        }    }}
           

In the code below, we use Alamofire to send a POST request to http://localhost:4000/simulate, which is a local web server (we will create this backend soon). In a real application, this will typically point to a real web server.

在下面的代碼中,我們使用Alamofire将POST請求發送到本地Web伺服器http:// localhost:4000 / simulate (我們将很快建立此後端)。 在真實的應用程式中,這通常指向真實的Web伺服器。

This endpoint does not take any parameters in order to keep the tutorial simple. We also do not need to do anything with the response. We just need the POST request to be sent every time the simulate visits button is pressed.

為了使本教程保持簡單,該端點不使用任何參數。 我們也不需要對響應做任何事情。 我們隻需要在每次按下模拟通路按鈕時發送POST請求即可。

使用Pusher捆綁實時功能 (Tie in realtime functionality using Pusher)

To make all this work, we will create a function that listens for events from Pusher and, when one is received, we save the value to

visitors

and then trigger the update chart function we created earlier.

為了使所有這些工作正常進行,我們将建立一個偵聽來自Pusher的事件的函數,并在收到一個事件後将其儲存給

visitors

,然後觸發我們先前建立的更新圖表函數。

To do this, open the

ViewController

and import the

PusherSwift

SDK under the Alamofire package at the top:

要做到這一點,打開

ViewController

和導入

PusherSwift

的Alamofire封裝頂部下SDK:

import PusherSwift
           

Next, we will declare a class property for the Pusher instance. We can do this right under the

visitors

declaration line:

接下來,我們将為Pusher執行個體聲明一個類屬性。 我們可以在

visitors

聲明行下直接執行此操作:

var pusher: Pusher!
           

Then after declaring the property, we need to add the function below to the class so it can listen to the events:

然後,在聲明屬性後,我們需要将以下函數添加到類中,以便它可以偵聽事件:

private func listenForChartUpdates() {    pusher = Pusher(        key: "PUSHER_KEY",         options: PusherClientOptions(            host: .cluster("PUSHER_CLUSTER")        )    )    let channel = pusher.subscribe("visitorsCount")    channel.bind(eventName: "addNumber", callback: { (data: Any?) -> Void in       if let data = data as? [String: AnyObject] {           let count = data["count"] as! Double           self.visitors.append(count)           self.updateChart()       }    })    pusher.connect()}
           

In the code above, we instantiate Pusher and pass in our key and the cluster (you can get your key and cluster from your Pusher application’s dashboard). We then subscribe to the

visitorsChannel

and bind to the event name

addNumber

on that channel.

在上面的代碼中,我們執行個體化Pusher并傳入我們的密鑰和叢集(您可以從Pusher應用程式的儀表闆擷取密鑰和叢集)。 然後,我們訂閱

visitorsChannel

和綁定到事件名稱

addNumber

該通道上。

When the event is triggered, we fire the logic in the callback which simply appends the count to

visitors

and then calls the

updateChart

function, which updates the actual Chart in realtime.

觸發事件後,我們将在回調中觸發邏輯,該邏輯将計數簡單地附加到

visitors

,然後調用

updateChart

函數,該函數實時更新實際的Chart。

Finally we call

pusher.connect()

which forms the connection to Pusher.

最後,我們調用

pusher.connect()

形成與Pusher的連接配接。

In the

viewDidLoad

function, just add a call to the

listenForChartUpdates

method:

viewDidLoad

函數中,隻需添加對

listenForChartUpdates

方法的調用:

override func viewDidLoad() {    super.viewDidLoad()    // ...stuff        listenForChartUpdates()}
           

That’s all! We have created our application in Xcode and we are ready for testing. However, to test, we need to create the backend that we send a

POST

request to when the button is clicked. To create this backend, we will be using Node.js. Let’s do that now.

就這樣! 我們已經在Xcode中建立了我們的應用程式,并且可以進行測試了。 但是,要進行測試,我們需要建立一個後端,單擊該按鈕後,我們将向該後端發送

POST

請求。 要建立此後端,我們将使用Node.js。 現在開始吧。

為我們的實時iOS圖表應用程式建立後端服務 (Creating the backend service for our realtime iOS chart application)

To get started, create a directory for the web application and then create some new files inside the directory:

首先,為Web應用程式建立一個目錄,然後在該目錄内建立一些新檔案:

File: index.js

檔案: index.js

// -------------------------------------------------------// Require Node dependencies// -------------------------------------------------------
           
let Pusher     = require('pusher');let express    = require('express');let bodyParser = require('body-parser');let app        = express();
           
// Instantiate Pusherlet pusher     = new Pusher(require('./config.js'));
           
// -------------------------------------------------------// Load express middlewares// -------------------------------------------------------
           
app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));
           
// -------------------------------------------------------// Simulate multiple changes to the visitor count value,// this way the chart will always update with different// values.// -------------------------------------------------------
           
app.post('/simulate', (req, res, next) => {    var loopCount = 0;    let sendToPusher = setInterval(function(){    let count = Math.floor((Math.random() * (100 - 1)) + 1)    pusher.trigger('visitorsCount', 'addNumber', {count:count})    loopCount++;    if (loopCount === 20) {        clearInterval(sendToPusher);    }    }, 2000);    res.json({success: 200})})
           
// Handle indexapp.get('/', (req, res) => {    res.json("It works!");});
           
// Handle 404'sapp.use((req, res, next) => {    let err = new Error('Not Found');    err.status = 404;    next(err);});
           
// -------------------------------------------------------// Serve application// -------------------------------------------------------
           
app.listen(4000, function(){    console.log('App listening on port 4000!')});
           

The file above is a simple Express application written in JavaScript. We instantiate all the packages we require and configure pusher using a config file we will create soon. Then we create a route

/simulate

and in this route we trigger the

addNumber

event in the

visitorCount

channel. This is the same channel and event the application is listening for.

上面的檔案是一個用JavaScript編寫的簡單Express應用程式。 我們執行個體化我們需要的所有軟體包,并使用即将建立的配置檔案配置pusher。 然後,我們建立一條路由

/simulate

并在此路由中在

visitorCount

通道中觸發

addNumber

事件。 這是應用程式正在偵聽的相同頻道和事件。

To make it a little easier, we use

setInterval

to send a random visitor count to the Pusher backend every 2000 milliseconds. After looping 20 times, the loop stops. This should be sufficient to test our application.

為了使操作更簡單,我們使用

setInterval

每隔2000毫秒将随機通路者計數發送到Pusher後端。 循環20次後,循環停止。 這應該足以測試我們的應用程式。

Create the next file config.js:

建立下一個檔案config.js :

module.exports = {    appId: 'PUSHER_APP_ID',    key: 'PUSHER_APP_KEY',    secret: 'PUSHER_APP_SECRET',    cluster: 'PUSHER_APP_CLUSTER',};
           

In this file, we simply declare dependencies.

在此檔案中,我們僅聲明依賴項。

Now open terminal and

cd

to the root of the web application directory. Run the commands below to install the NPM dependencies, and run the application respectively:

現在打開終端,并

cd

到Web應用程式目錄的根目錄。 運作以下指令以安裝NPM依賴項,并分别運作該應用程式:

$ npm install$ node index.js
           

When installation is complete and the application is ready, you should see the output below:

安裝完成并且應用程式準備就緒後,您應該看到以下輸出:

測試應用程式 (Testing the application)

Once you have your local node web server running, you will need to make some changes so your application can talk to the local web server. In the

info.plist

file, make the following changes:

一旦運作了本地節點Web伺服器,就需要進行一些更改,以便您的應用程式可以與本地Web伺服器通信。 在

info.plist

檔案中,進行以下更改:

With this change, you can build and run your application and it will talk directly with your local web application.

進行此更改後,您可以建構和運作您的應用程式,它将直接與本地Web應用程式通信。

結論 (Conclusion)

This article has shown you how you can combine Pusher and the Charts package to create a realtime iOS chart application. There are many other chart types you can create using the package but, for brevity, we have done the easiest. You can explore the other chart types and even pass in multiple data points per request.

本文向您展示了如何結合Pusher和Charts包來建立實時iOS圖表應用程式。 您可以使用該軟體包建立許多其他圖表類型,但為簡便起見,我們已做得最簡單。 您可以浏覽其他圖表類型,甚至可以按請求傳遞多個資料點。

This post first appeared on the Pusher blog.

這篇文章首先出現在Pusher部落格上。

翻譯自: https://www.freecodecamp.org/news/how-to-build-a-realtime-chart-in-ios-34a07410d50d/

ios 圖表