辛宝Otto

辛宝Otto 的玄酒清谈

北漂前端程序员儿 / 探索新事物 / Web Worker 主播之一/内向话痨
xiaoyuzhou
email

Native client enthusiasts are ecstatic: uni-app now supports native hybrid development!

Native developers are ecstatic: uni-app x supports native hybrid development!

Background#

Recently, uni-app x released a new version, and one of the points is that uni-app x 4.25 supports native hybrid development, which means you can directly use kotlin/java/swift code. Native developers can go all out!

Added support for Kotlin, Java, and Swift code hybrid development in the UTS plugin of the compiler

Like many others, I need to use uni-app x to develop apps, but I am unfamiliar with native development (hereinafter referred to as "native development") and not familiar with related domain knowledge. UTS language can be used for native function development.

There are also many experienced native developers participating in the development of uni-app x, who are familiar with various underlying details of native development and prefer to use existing native development experience.

These two different groups of people have different needs and may provide different product suggestions from different perspectives:

  • Front-end developers feedback that page layout and business development are fast, but they are not familiar with native development and cannot solve problems.
  • Native developers feedback that they hope to reuse existing native SDKs and native toolkits.

Everyone has the same goal, to speed up app development and complete it early without working overtime!

This article briefly introduces the basic concepts, related usage, and advanced improvements of native hybrid development.

Why is there native hybrid development?#

Who is the target audience for this feature, what is its use, and does it affect me?

When developing applications using uni-app x in the past, in order to implement business logic and call native functions, it was necessary to use the UTS language to write compatible code and convert it to Kotlin and Swift through the compiler.

This is more friendly to front-end developers: because the syntax of UTS is similar to TS, as long as they know how to write native code, they can get started by making a few conversions. This enables front-end engineers to have the ability to call native functions.

On the other hand, there are some complaints from experienced native developers. They have to learn UTS, UTS plugins, and other things, and hope to be able to reuse their native development knowledge in the future.

This update supports native hybrid development in the UTS plugin. Let's take an example to illustrate.

Related articles:

  • [[How to quickly learn and test Swift and UIKit code?]]
  • [[How to quickly learn and test Android Kotlin code?]]

Here, iOS is mainly used to introduce the platform, and Android is similar. For a consistent reading experience, Android-related code will be provided at the end of the article.

Let's start with the concept.

Querying the Current Battery Level in iOS#

Users familiar with uni-app x may have heard several examples of querying the current battery level on a mobile phone. This is a classic case.

Suppose I want to query the current battery level in the app. If the current battery level is relatively high, such as above 80%, the app should use advanced animations. If it is below this value, it should use normal animations.

If you use uni-app x to get the current battery level, this requirement is a native requirement and requires calling the client's API to obtain it. uni-app x has already encapsulated this API, and you can directly use uni.getBatteryInfo to get it.

Here, let's pretend that it doesn't exist and we need to implement it ourselves.

Example of Native iOS Code#

You can find out the logic of querying the battery level in iOS by asking native colleagues, asking AI, or referring to the open source code of uni-app x.

import UIKit

func getBatteryLevel() -> Float {
    // Enable battery monitoring
    UIDevice.current.isBatteryMonitoringEnabled = true
    
    // Get the current battery level
    let batteryLevel = UIDevice.current.batteryLevel
    // Convert to percentage
    return batteryLevel * 100
}

// Get the battery level and print it
let currentBatteryLevel = getBatteryLevel()
print("Current battery level: \(currentBatteryLevel)%")

Before Hybrid Development#

Before uni-app x supported hybrid development, we needed to translate the above code using UTS, and convert it to native code through the UTS compiler: know how to write native code - translate to UTS - translate to Swift.

The UTS code is roughly as follows, with function export, formatting, and other logic removed.

import { UIDevice } from "UIKit";
UIDevice.current.isBatteryMonitoringEnabled = true
const batteryLevel = Number(UIDevice.current.batteryLevel * 100)

By splitting the logic into UTS plugins, the UTS compiler can convert it to Swift code during compilation.

The process of importing packages on the Android platform is not exactly the same. Generally, it is recommended to implement functionality according to the platform.

After Hybrid Development#

With native hybrid development, many things become much simpler. If you are not familiar with UTS plugin development, you can refer to [[Beginner's Guide: Packaging UTS Plugins]], which mainly introduces how to develop UTS plugins. This article mainly demonstrates the general idea of hybrid development and does not go into details.

The classic directory structure of a UTS plugin is as follows:

uni_modules
- webworker-batteryStatus
-- utssdk
--- app-ios
---- index.uts
-- package.json

In the app-ios/index.uts file of the UTS plugin, create NativeCode.swift, which is a native swift file as the name suggests.

The content of the NativeCode.swift file is as follows, which is a recommended way by the official.

import UIKit

public class NativeCode {
  static func getBatteryLevelSwift() -> Float {
      // Enable battery monitoring
      UIDevice.current.isBatteryMonitoringEnabled = true
      
      // Get the current battery level
      let batteryLevel = UIDevice.current.batteryLevel
      // Convert to percentage
      return batteryLevel * 100
  }
}

How to call it in UTS?

The code in index.uts is as follows

export function getBatteryLevelSwift() : Float {
  return NativeCode.getBatteryLevelSwift()
}

Using it is very simple, just import the package and call the method.

<template>
  <view>
    <view>{{currentLevel}}</view>
    <button @click="getLevel">Battery Level</button>
  </view>
</template>

<script setup>
  import { getBatteryLevelSwift  } from '../../uni_modules/webworker-batteryLevel'
  const currentLevel = ref(0)
  const getLevel = () => {
    console.log('click button')
    // console.log(getBatteryLevelSwift())
    const res = getBatteryLevelSwift()
    currentLevel.value = res
  }
</script>

image.png

By

  • Native development logic
  • UTS packaging logic
  • Calling in uvue

Hybrid development can be easily achieved.

Implementing Hybrid Development in Android#

Similar to iOS, add index.uts and NativeCode.kt to the app-android directory of uni_moduels.

The content of NativeCode.kt is roughly as follows

package uts.sdk.modules.ottoBatteryLevel;
import android.content.Context
import android.os.BatteryManager

object NativeCode {
  fun getBatteryLevel(context: Context): Int {
      val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
      val batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
      return batteryLevel
  }
}

The content of index.uts is as follows

import Context from "android.content.Context";

export function getBatteryLevel() : Int {
  const context = UTSAndroid.getAppContext()!;
  return NativeCode.getBatteryLevel(context)
}

The rest is the same as iOS, calling the uts plugin in uvue.

What's Next?#

I hope that through this article, you can have a further understanding of UTS plugin development, native hybrid development, and uni-app x development.

With this powerful tool, you can explore more content. What can you do next?

Learn more details by implementing the official demo#

The official hello uts repository has been open sourced, and you can learn more details from this case.

uni_modules/uts-tests/utssdk/NativeCode.uts · dev · DCloud / Hello UTS · GitCode

Learn more technical details from the official documentation#

It provides a detailed explanation of the origin and details of native hybrid development.
https://doc.dcloud.net.cn/uni-app-x/plugin/uts-plugin-hybrid.htm

Learn UTS plugin development#

Refer to the article "[Beginner's Guide: Packaging UTS Plugins]".

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.