当前位置: 首页 > 工具软件 > Swift Crypto > 使用案例 >

swift加密_如何使用Swift和Laravel创建加密跟踪应用程序的后端

元英朗
2023-12-01

swift加密

by Neo Ighodaro

由新Ighodaro

如何使用Swift和Laravel创建加密跟踪应用程序的后端 (How to create the backend of a crypto tracking app using Swift and Laravel)

第1部分 (Part 1)

You will need the following installed on your machine: Xcode, the Laravel CLI, SQLite and Cocoapods. Familiarity with the Xcode IDE will be helpful.
您将需要在计算机上安装以下软件:Xcode,Laravel CLI,SQLite和Cocoapods。 熟悉Xcode IDE将有所帮助。

介绍 (Introduction)

Cryptocurrency has been and is still one of the biggest trends this year. With currencies like Bitcoin reaching record highs and new companies creating tokens and offerings, it’s showing just how much potential cryptocurrencies have. However, cryptocurrency prices are erratic and can fall or climb at a moment’s notice, so it’s always a good idea to keep tabs on the changes.

加密货币一直是并且仍然是今年最大的趋势之一。 随着像比特币这样的货币达到创纪录的高位,以及新公司创建代币和产品,它正在显示出多少潜在的加密货币。 但是,加密货币的价格不稳定,并可能在瞬间通知上下波动,因此,始终密切注意变化是一个好主意。

In this article, we will be building an application that keeps tabs on changes to the crypto market. The application will focus on BTC and ETH and will allow users of the application to set minimum and maximum amounts when they would like to be notified about the coin’s current price. The application will be built using Swift, Laravel, Pusher Channels, and Pusher Beams.

在本文中,我们将构建一个可密切关注加密市场变化的应用程序。 该应用程序将重点关注BTC和ETH,并允许应用程序的用户在希望收到有关代币当前价格的通知时设置最小和最大金额。 该应用程序将使用Swift,Laravel,Pusher Channels和Pusher Beams构建。

先决条件 (Prerequisites)

To follow along you need the following requirements:

要遵循,您需要满足以下要求:

我们将要建设的 (What we will be building)

We will start out by building the backend of the application using Laravel. Then we will build the iOS application using Swift. If you want to test the push notifications then you will need to run the application on a live device.

我们将从使用Laravel构建应用程序的后端开始。 然后,我们将使用Swift构建iOS应用程序。 如果要测试推送通知,则需要在实时设备上运行该应用程序。

客户端应用程序将如何工作 (How the client application will work)

For the client app, the iOS application, we will create a simple list that will display the available currencies and the current prices to the dollar. Whenever the price of the cryptocurrency changes, we will trigger an event using Pusher Channels so the prices are updated.

对于客户端应用程序(iOS应用程序),我们将创建一个简单列表,该列表将显示可用货币和美元的当前价格。 每当加密货币的价格发生变化时,我们都会使用Pusher Channels触发事件,以便更新价格。

From the application, you will be able to set a minimum and maximum price change when you want to be alerted. For instance, you can configure the application to send a push notification to the application when the price of one Etherium (ETH) goes below $500. You can also configure the application to receive a notification when the price of Bitcoin goes above $5000.

通过该应用程序,您可以在想要收到警报时设置最小和最大价格变化。 例如,您可以将应用程序配置为在一个以太网(ETH)的价格低于$ 500时向应用程序发送推送通知。 您还可以将应用程序配置为在比特币价格超过5000美元时接收通知。

后端应用程序将如何工作 (How the backend application will work)

For the backend application, we will be using Laravel and we will create endpoints that allow a user update the settings and load the settings for a device. The API will be responsible for checking the current prices of the cryptocurrency and sending both a Channels update and a Beams notification when the price changes.

对于后端应用程序,我们将使用Laravel,并将创建允许用户更新设置并加载设备设置的端点。 该API将负责检查加密货币的当前价格,并在价格变化时发送通道更新和Beams通知。

However, because the prices don’t change very predictably, we will be simulating the currency changes so we can preview the application in action. We will also be using task scheduling in Laravel to trigger the checks for the current currency prices.

但是,由于价格变化不是非常可预测的,因此我们将模拟货币变化,以便可以预览实际的应用程序。 我们还将在Laravel中使用任务调度来触发对当前货币价格的检查。

In a production environment we will set the scheduler as a cronjob, but because we are in development, we will manually run the command to trigger price changes.

在生产环境中,我们会将调度程序设置为cronjob,但是由于我们正在开发中,因此我们将手动运行命令以触发价格变动。

应用程序的外观 (How the application will look)

When we are done with the application, here’s how the application will look:

处理完应用程序后,以下是该应用程序的外观:

Let’s get started.

让我们开始吧。

设置推杆和通道 (Setting up Pusher Beams and Channels)

设置推送器通道 (Setting up Pusher Channels)

Log in to your Pusher dashboard. If you don’t have an account, create one. Your dashboard should look like this:

登录到Pusher仪表板 。 如果您没有帐户,请创建一个。 您的仪表板应如下所示:

Create a new Channels app. You can easily do this by clicking the big Create new Channels app card at the bottom right. When you create a new app, you are provided with keys. Keep them safe as you will soon need them.

创建一个新的频道应用。 您可以通过点击右下角的大的Create new Channels应用卡轻松地做到这一点。 创建新应用时,会为您提供密钥。 确保它们安全,因为您很快就会需要它们。

设置推杆 (Setting up Pusher Beams)

Next, log in to the new Pusher dashboard, in here we will create a Pusher Beams instance. You should sign up if you don’t have an account yet. Click on the Beams button on the sidebar then click Create, this will launch a pop up to Create a new Beams instance. Name it cryptoalat.

接下来,登录到新的Pusher仪表板 ,在这里我们将创建Pusher Beams实例。 如果您还没有帐户,请先注册。 单击侧边栏上的Beams按钮,然后单击Create ,这将启动一个弹出窗口以创建一个新的Beams实例 。 将其命名为cryptoalat

As soon as you create the instance, you will be presented with a quickstart guide. Select the IOS quickstart and follow through the wizard.

创建实例后,将为您提供快速入门指南。 选择IOS快速入门,然后按照向导进行操作。

When you are done creating the Beams application, you will be provided with an instance ID and a secret key, we will need these later.

完成创建Beams应用程序后,将为您提供实例ID和密钥,稍后我们将需要它们。

设置您的后端应用程序 (Setting up your backend application)

In your terminal, run the command below to create a new Laravel project:

在您的终端中,运行以下命令以创建一个新的Laravel项目:

$ laravel new cryptoapi

This command will create a new Laravel project and install all the required Laravel dependencies.

该命令将创建一个新的Laravel项目并安装所有必需的Laravel依赖项。

Next, let’s install some of the project specific dependencies. Open the composer.json file and in the require property, add the following dependencies:

接下来,让我们安装一些项目特定的依赖项。 打开composer.json文件,并在require属性中添加以下依赖项:

// File: composer.json
    "require": {
        [...]
        
        "neo/pusher-beams": "^1.0",
        "pusher/pusher-php-server": "~3.0"
    },

Now run the command below to install these dependencies.

现在运行以下命令以安装这些依赖项。

$ composer update

When the installation is complete, open the project in a text editor of your choice. Visual Studio Code is pretty nice.

安装完成后,在您选择的文本编辑器中打开项目。 Visual Studio Code非常不错。

设置我们的推杆梁库 (Setting up our Pusher Beams library)

The first thing we want to do is set up the Pusher Beams library we just pulled in using composer. To set up, open the .env file and add the following keys:

我们要做的第一件事是设置我们刚刚使用作曲家引入的Pusher Beams库 。 要进行设置,请打开.env文件并添加以下键:

PUSHER_BEAMS_SECRET_KEY="PUSHER_BEAMS_SECRET_KEY"
    PUSHER_BEAMS_INSTANCE_ID="PUSHER_BEAMS_INSTANCE_ID"

You should replace the PUSHER_BEAMS_* placeholders with the keys you got when setting up your Beams application.

您应将PUSHER_BEAMS_*占位符替换为设置Beams应用程序时获得的键。

Next, open the config/broadcasting.php file and scroll until you see the connections key. In there, you’ll have the pusher settings, add the following to the pusher configuration:

接下来,打开config/broadcasting.php文件并滚动,直到看到connections键。 在其中,您将具有pusher设置,将以下内容添加到pusher配置中:

'pusher' => [
        // [...]
        
        'beams' => [
            'secret_key' => env('PUSHER_BEAMS_SECRET_KEY'),
            'instance_id' => env('PUSHER_BEAMS_INSTANCE_ID'),
        ],
    ],

设置我们的Pusher Channels库 (Setting up our Pusher Channels library)

The next step is to set up Pusher Channels. Laravel comes with native support for Pusher Channels so we do not need to do much to set it up.

下一步是设置推入通道。 Laravel附带了对Pusher Channels的本地支持,因此我们无需做太多设置。

Open the .env file and update the following keys below:

打开.env文件,然后更新以下键:

BROADCAST_DRIVER=pusher

    // [...]
    
    PUSHER_APP_ID="PUSHER_APP_ID"
    PUSHER_APP_KEY="PUSHER_APP_KEY"
    PUSHER_APP_SECRET="PUSHER_APP_SECRET"
    PUSHER_APP_CLUSTER="PUSHER_APP_CLUSTER"

Above you set the BROADCAST_DRIVER to pusher and then for the other PUSHER_APP_* keys, replace the placeholders with the keys gotten from your Pusher dashboard. That’s all we need to do to set up Pusher Channels for this application.

在上方,将BROADCAST_DRIVER设置为pusher ,然后对于其他PUSHER_APP_*键,将占位符替换为从Pusher仪表板获得的键。 这就是我们为此应用程序设置推送器通道所需要做的全部工作。

构建后端应用程序 (Building the backend application)

Now that we have set up all the dependencies, we can start building the application. We will start by creating the routes. However, instead of creating controllers to hook into the routes, we will be adding the logic directly to the routes.

现在我们已经设置了所有依赖项,我们可以开始构建应用程序了。 我们将从创建路线开始。 但是,我们将创建逻辑直接添加到路由中,而不是创建控制器以挂接到路由中。

设置数据库,迁移和模型 (Setting up the database, migration, and model)

Since we will be working with a database, we need to set up the database we are going to be working with. To make things easy we will be using SQLite. Create an empty database.sqlite file in the database directory.

由于我们将使用数据库,因此我们需要设置将要使用的数据库。 为了使事情变得简单,我们将使用SQLite。 在database目录中创建一个空的database.sqlite文件。

Open the .env file and replace:

打开.env文件并替换:

DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=homestead
    DB_USERNAME=homestead
    DB_PASSWORD=secret

With

DB_CONNECTION=sqlite
    DB_DATABASE=/full/path/to/your/database.sqlite

Next, let’s create a migration for the devices table. We will use this table to store devices and their notification settings. This will help us know what devices to send push notifications to.

接下来,让我们为devices表创建一个迁移。 我们将使用此表存储设备及其通知设置。 这将帮助我们了解向哪些设备发送推送通知。

Run the command below to create the migration and model:

运行以下命令以创建迁移和模型:

$ php artisan make:model Device -m

The -m flag will instruct artisan to create a migration alongside the model.

-m标志将指示技术人员与模型一起创建迁移。

This command will generate two files, the migration file in the database/migrations and the model in the app directory. Let’s edit the migration file first.

此命令将生成两个文件, database/migrations的迁移文件和app目录中的模型。 让我们首先编辑迁移文件。

Open the *_create_devices_table.php migration file in the database/migrations directory and replace the contents with the following:

打开database/migrations目录中的*_create_devices_table.php迁移文件,并将内容替换为以下内容:

<?php

    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateDevicesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('devices', function (Blueprint $table) {
                $table->increments('id');
                $table->string('uuid')->unique();
                $table->float('btc_min_notify')->default(0);
                $table->float('btc_max_notify')->default(0);
                $table->float('eth_min_notify')->default(0);
                $table->float('eth_max_notify')->default(0);
            });
        }
        
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('devices');
        }
    }

In the up method, we have defined the structure of the devices table. We have the uuid field which will be a unique string for each device registered. We have two btc_notify fields which are there to save the minimum and maximum prices of BTC at which point the device should be notified. Same applies to the* eth_*_notify fields.

up方法中,我们定义了devices表的结构。 我们有uuid字段,它将是每个注册设备的唯一字符串。 我们有两个btc_notify字段,用于保存BTC的最低和最高价格,此时应通知设备。 * eth_*_notify字段也是如此。

To run the migration, run the command below:

要运行迁移,请运行以下命令:

$ php artisan migrate

Open the app/Device.php model and replace the contents with the code below:

打开app/Device.php模型,并将内容替换为以下代码:

<?php
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Notifications\Notifiable;
    
    class Device extends Model
    {
        use Notifiable;
        
        public $timestamps = false;
        
        protected $fillable = [
            'uuid', 
            'btc_min_notify', 
            'btc_max_notify', 
            'eth_min_notify', 
            'eth_max_notify',
        ];
        
        protected $cast = [
            'btc_min_notify' => 'float',
            'btc_max_notify' => 'float',
            'eth_min_notify' => 'float',
            'eth_max_notify' => 'float'
        ];
        
        public function scopeAffected($query, string $currency, $currentPrice)
        {
            return $query->where(function ($q) use ($currency, $currentPrice) {
                $q->where("${currency}_min_notify", '>', 0)
                  ->where("${currency}_min_notify", '>', $currentPrice);
            })->orWhere(function ($q) use ($currency, $currentPrice) {
                $q->where("${currency}_max_notify", '>', 0)
                  ->where("${currency}_max_notify", '<', $currentPrice);
            });
        }
    }

In the model above, we have set the $timestamps property to false to make sure that Eloquent does not try to update the created_at and updated_at fields, which is the normal behavior.

在上面的模型中,我们将$timestamps属性设置为false ,以确保Eloquent不会尝试更新created_atupdated_at字段,这是正常行为。

We also have the scopeAffected method which is an example of an Eloquent scope. We use this to get the affected devices after a price change has occurred on a currency. So if, for instance, BTC’s price drops, this method will check the devices and the settings to see the devices that need to be notified of this change.

我们还有scopeAffected方法,这是scopeAffected 范围的一个示例。 货币价格发生变化后,我们用它来获取受影响的设备。 因此,例如,如果BTC的价格下跌,此方法将检查设备和设置以查看需要将此更改通知的设备。

Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered “popular”. To define a scope, prefix an Eloquent model method with scope. - Laravel documentation.

局部作用域使您可以定义常见的约束集,可以在整个应用程序中轻松地重用这些约束集。 例如,您可能需要经常检索所有被认为“受欢迎”的用户。 要定义范围,请在Eloquent模型方法前加上scope -Laravel文档

We will use this scope later in our application when we need to know what devices to send push notifications to.

当我们需要知道向哪个设备发送推送通知时,将在我们的应用程序中稍后使用此范围。

创建路线 (Creating the routes)

Open the routes/api.php file and replace the contents of the file with the following code:

打开routes/api.php文件, routes/api.php文件内容替换为以下代码:

// File: routes/api.php
    <?php
    use App\Device;
    use Illuminate\Http\Request;

Next, let’s add the first route. Append the code below to the routes file:

接下来,让我们添加第一个路线。 将以下代码添加到路由文件:

// File: routes/api.php
    Route::get('/settings', function (Request $request) {
        return Device::whereUuid($request->query('u'))->firstOrFail()['settings'];
    });

In the route above, we are returning the settings for the device supplied in the u query parameter. This means if a registered device hits the /settings endpoint and passes the device UUID through the u parameter, the settings for that device will be returned.

在上面的路线中,我们返回u查询参数中提供的设备的设置。 这意味着,如果已注册的设备命中/settings端点并通过u参数传递设备UUID,则将返回该设备的设置。

Next, in the same routes file, paste the following at the bottom of the file:

接下来,在相同的路由文件中,将以下内容粘贴到文件底部:

Route::post('/settings', function (Request $request) {
        $settings = $request->validate([
            'btc_min_notify' => 'int|min:0',
            'btc_max_notify' => 'int|min:0',
            'eth_min_notify' => 'int|min:0',
            'eth_max_notify' => 'int|min:0',
        ]);
        
        $settings = array_filter($settings, function ($value) { return $value > 0; });
        
        $device = Device::firstOrNew(['uuid' => $request->query('u')]);
        $device->fill($settings);
        $saved = $device->save();
        
        return response()->json([
            'status' => $saved ? 'success' : 'failure'
        ], $saved ? 200 : 400);
    });

Above, we have defined the route for the POST /settings route. This route saves settings to the database. It will create a new entry if the setting does not already exist or will update the existing one if it does.

上面,我们为POST /settings路由定义了路由。 此路由将设置保存到数据库。 如果该设置尚不存在,它将创建一个新条目,或者如果存在则将更新现有条目。

That’s all for the routes.

仅此而已。

创建作业,事件和通知程序 (Creating the jobs, events, and notifiers)

Next, we need to create the Laravel job that will run at intervals to check if there is a change in the currency price.

接下来,我们需要创建Laravel作业 ,该作业将定期运行以检查货币价格是否发生变化。

Run the command below to create a new Laravel job:

运行以下命令以创建新的Laravel作业:

$ php artisan make:job CheckPrices

This will create a new CheckPrices class in the app directory. Open that class and replace the contents with the following:

这将在app目录中创建一个新的CheckPrices类。 打开该类,然后将内容替换为以下内容:

<?php

    namespace App\Jobs;
    
    use App\Device;
    use Illuminate\Bus\Queueable;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    use App\Events\CurrencyUpdated;
    use App\Notifications\CoinPriceChanged;
    
    class CheckPrices implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
        
        protected $supportedCurrencies = ['ETH', 'BTC'];
        
        /**
         * Execute the job.
         *
         * @return void
         */
        public function handle()
        {
            $payload = $this->getPricesForSupportedCurrencies();
            
            if (!empty($payload)) {
                $this->triggerPusherUpdate($payload);
                $this->triggerPossiblePushNotification($payload);
            }
        }
        
        private function triggerPusherUpdate($payload)
        {
            event(new CurrencyUpdated($payload));
        }
        
        private function triggerPossiblePushNotification($payload)
        {
            foreach ($this->supportedCurrencies as $currency) {
                $currentPrice = $payload[$currency]['current'];
                
                $currency = strtolower($currency);
                
                foreach (Device::affected($currency, $currentPrice)->get() as $device) {
                    $device->notify(new CoinPriceChanged($currency, $device, $payload));
                }
            }
        }
        
        public function getPricesForSupportedCurrencies(): array
        {
            $payload = [];
            
            foreach ($this->supportedCurrencies as $currency) {
                if (config('app.debug') === true) {
                    $response = [
                        $currency => [
                            'USD' => (float) rand(100, 15000)
                        ]
                    ];
                } else {
                    $url = "https://min-api.cryptocompare.com/data/pricehistorical?fsym={$currency}&tsyms=USD&ts={$timestamp}";
                    
                    $response = json_decode(file_get_contents($url), true);
                }
                
                if (json_last_error() === JSON_ERROR_NONE) {
                    $currentPrice = $response[$currency]['USD'];
                    
                    $previousPrice = cache()->get("PRICE_${currency}", false);
                    
                    if ($previousPrice == false or $previousPrice !== $currentPrice) {
                        $payload[$currency] = [
                            'current' => $currentPrice,
                            'previous' => $previousPrice,
                        ];
                    }
                    
                    cache()->put("PRICE_${currency}", $currentPrice, (24 * 60 * 60));
                }
            }
            
            return $payload;
        }
    }

In the class above, we implement the ShouldQueue interface. This makes it so that the job can and will be queued. In a production server, queueing jobs makes your application faster as it queues jobs that might take a while to execute for later execution.

在上面的类中,我们实现了ShouldQueue接口。 这样一来,作业就可以并且将排队。 在生产服务器中,排队作业使您的应用程序更快,因为它会将可能需要一段时间才能执行的作业排队,以供以后执行。

We have four methods in this class. The first one is the handle method. This one is called automatically when the job is executed. In this method, we fetch the prices for the available currencies and then check if the price has changed. If it has, we publish a Pusher Channel event and then check if there are any devices that need to be notified based on the user’s settings. If there are any, we send a push notification to that device.

此类中有四种方法。 第一个是handle方法。 执行作业时会自动调用此选项。 在这种方法中,我们获取可用货币的价格,然后检查价格是否已更改。 如果有的话,我们将发布Pusher Channel事件,然后根据用户设置检查是否需要通知任何设备。 如果有的话,我们会向该设备发送推送通知。

We have the triggerPusherUpdate method which triggers a CurrencyUpdated event. We will create this event in the next section. We also have a triggerPossiblePushNotification method which gets the list of devices which should be notified of the currency change and then notifies the user using the CoinPriceChanged class, which we will create in the next section.

我们有triggerPusherUpdate方法,该方法触发CurrencyUpdated事件。 我们将在下一部分中创建此事件。 我们还有一个triggerPossiblePushNotification方法,该方法获取应通知币种变化的设备列表,然后使用CoinPriceChanged类通知用户,该类将在下一部分中创建。

Lastly, we have the getPricesForSupportedCurrencies method which just fetches the current price of a currency. In this method, we have a debug mode that simulates the current price of a currency.

最后,我们有getPricesForSupportedCurrencies方法,该方法只获取货币的当前价格。 在这种方法中,我们有一个调试模式,可以模拟货币的当前价格。

To make sure this class we just created is scheduled properly, open the app/Console/Kernel.php file and in the schedule method, add the following code to the schedule method:

为确保我们刚刚创建的此类已正确安排,请打开app/Console/Kernel.php文件,然后在schedule方法中,将以下代码添加到schedule方法:

$schedule->job(new \App\Jobs\CheckPrices)->everyMinute();

Now every time we run the command php artisan schedule:run all the jobs in this schedule method will be run. Normally, in a production environment, we will need to add the schedule command as a cronjob, however, we will run this command manually.

现在,每次我们运行命令php artisan schedule:run ,将运行此schedule方法中的所有作业。 通常,在生产环境中,我们需要将schedule命令添加为cronjob,但是,我们将手动运行此命令。

The next thing to do will be to create the notifiers and events. In your terminal, run the following commands:

接下来要做的是创建通知程序和事件。 在您的终端中,运行以下命令:

$ php artisan make:event CurrencyUpdated    $ php artisan make:notification CoinPriceChanged

This will create a class in the Events and Notifications directories.

这将在“ Events和“ Notifications目录中创建一个类。

In the event class, CurrencyUpdated paste the following code:

事件类中, CurrencyUpdated粘贴以下代码:

<?php

    namespace App\Events;
    
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    
    class CurrencyUpdated implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
        
        public $payload;
        
        public function __construct($payload)
        {
            $this->payload = $payload;
        }
        
        public function broadcastOn()
        {
            return new Channel('currency-update');
        }
        
        public function broadcastAs()
        {
            return 'currency.updated';
        }
    }

In the event class above, we have the broadcastOn method that specifies the Pusher channel we want to broadcast an event on. We also have the broadcastAs method which specifies the name of the event we want to broadcast to the channel.

在上面的事件类中,我们具有broadcastOn方法,该方法指定要在其上广播事件的Pusher频道。 我们还具有broadcastAs方法,该方法指定我们要广播到频道的事件的名称。

In the CoinPriceChanged notification class, replace the contents with the following code:

CoinPriceChanged 通知类中,将内容替换为以下代码:

<?php

    namespace App\Notifications;
    
    use App\Device;
    use Illuminate\Bus\Queueable;
    use Neo\PusherBeams\PusherBeams;
    use Neo\PusherBeams\PusherMessage;
    use Illuminate\Notifications\Notification;
    
    class CoinPriceChanged extends Notification
    {
        use Queueable;
        
        private $currency;
        private $device;
        private $payload;
        
        public function __construct(string $currency, Device $device, array $payload)
        {
            $this->currency = $currency;
            $this->device = $device;
            $this->payload = $payload;
        }
        
        public function via($notifiable)
        {
            return [PusherBeams::class];
        }
        
        public function toPushNotification($notifiable)
        {
            $currentPrice = $this->payload[strtoupper($this->currency)]['current'];
            
            $previousPrice = $this->payload[strtoupper($this->currency)]['current'];
            
            $direction = $currentPrice > $previousPrice ? 'climbed' : 'dropped';
            
            $currentPriceFormatted = number_format($currentPrice);
            
            return PusherMessage::create()
                    ->iOS()
                    ->sound('success')
                    ->title("Price of {$this->currency} has {$direction}")
                    ->body("The price of {$this->currency} has {$direction} and is now \${$currentPriceFormatted}");
        }
        
        public function pushNotificationInterest()
        {
            $uuid = strtolower(str_replace('-', '_', $this->device->uuid));
            
            return "{$uuid}_{$this->currency}_changed";
        }
    }

In the class above we have the toPushNotification class which prepares the push notification using the Pusher Beams library. We also have the pushNotificationInterest method which sets the name for the interest of the push notification depending on the currency and device ID.

在上面的类中,我们有toPushNotification类,该类使用Pusher Beams库准备推送通知。 我们还有pushNotificationInterest方法,该方法根据货币和设备ID来设置推送通知的名称。

That’s all for the backend, now just run the command below to start the server:

这就是后端的全部内容,现在只需运行以下命令来启动服务器:

$ php artisan serve

This will start a PHP server with our application running. Also if you need to manually trigger a currency change, run the command below:

这将启动运行我们的应用程序PHP服务器。 另外,如果您需要手动触发货币更改,请运行以下命令:

$ php artisan schedule:run

Now that we are done with the backend, we can create the application using Swift and Xcode.

现在我们已经完成了后端,我们可以使用Swift和Xcode创建应用程序。

结论 (Conclusion)

In this part of the article, we have created the backend for our cryptocurrency alert application. In the next part, we will be seeing how we can create the application that will consume the API we just created in this part.

在本文的这一部分中,我们为我们的加密货币警报应用程序创建了后端。 在下一部分中 ,我们将看到如何创建应用程序,该应用程序将使用我们在本部分中刚刚创建的API。

The source code to this application is available on GitHub.

该应用程序的源代码可在GitHub找到

This article was first published to pusher.

本文最初是发布给推杆的。

翻译自: https://www.freecodecamp.org/news/how-to-create-the-backend-of-a-crypto-tracking-app-using-swift-and-laravel-1d9122bc290b/

swift加密

 类似资料: