辛宝Otto

辛宝Otto 的玄酒清谈

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

How to quickly learn and test Swift and UIKit code?

My Background#

I am an ordinary front-end developer. I have not studied iOS development before, but sometimes I need to implement Swift code and wrap it as a plugin to call native functions in an app.

After the support for native hybrid development in uni-app x 4.25, there are more things that can be done.

For example, I want to encapsulate a function to get the current battery level of the phone, or to determine if the current system theme is dark mode, or to play a piece of music when a button is pressed.

Testing in JS web development is easy. Just open a web page in a browser, press F12 to open the console, and you can run JS code and get responses. However, this is not possible in native client development.

So, how can I learn as little irrelevant knowledge as possible and quickly test and experiment with UIKit and Swift code?

This article documents my learning process and is aimed at readers who, like me, are ignorant of pure front-end and client-side development. If I gain a deeper understanding in the future, I will try to modify the details. Readers should also exercise caution.

Where does the code come from?#

Previously, I recommended quickly reading the official documentation to understand the outline before conducting testing and practice. Now, with AI, it is more suitable to ask AI, for example:

How can I use UIKit to get the current battery level and write a function that returns the result? I want to call the function and print the result.

Once you know how to get the code, how do you test it? Considering that I don't need to systematically master the use of Xcode at this stage, this leads to the following topic.

Quick Testing of UIKit?#

How can I quickly learn UIKit and Swift?

Through my exploration, I found two solutions for testing: creating a regular project and using a playground. Let's discuss each of them below.

The following solutions are based on Xcode 15.4. As versions iterate, some screenshots may change, but major changes are not expected.

1. Creating a Regular Project#

Setting Up the Basic Template#

Open Xcode and choose to create a new project, which will bring up the following dialog box.

image.png

Note: Select iOS as the top platform, and do not choose the default Multiplatform option.

Click Next to get the following dialog box.

image.png

Tips:

  • Enter any name for Product Name.
  • Choose any team. I chose None.
  • For Org ID, the default or any format like a.b.c will do.
  • For Interface, I tried selecting Storyboard instead of SwiftUI.
  • Choose Swift for Language.
  • Choose None for Storage.
  • Deselect Include Tests.

Click Next, and the following popup window will appear, asking you to choose the location to store the code.

image.png

Finally, select Create to complete the creation of a regular project.

Testing the Demo Code#

With the project created, we can now test Swift code blocks.

image.png

Following the prompts in the image above, open ViewController.swift and delete everything, then paste the code I provided.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
       
        // Get the battery level and print it
        let currentBatteryLevel = getBatteryLevel()
        print("Current battery level: \(currentBatteryLevel)%")
    }

    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
    }
}

This code will call the getBatteryLevel() method and print the result to the console after the application launches.

This code will retrieve the battery level and return the data.

After pasting the code, select the simulator at the top and click Run. Wait a moment, and you will see the result in the console.

image.png

The above is the testing solution for a regular project. Although it is slightly more complex, it is more organized and is the most common template.

Next, I will introduce a simpler solution that I learned from AI.

2. Creating a Playground Project#

In Xcode, choose to create a playground. I don't know why, but the default project creation does not include this template.

Setting Up the Basic Template#

You must use the following method:

Open Xcode's startup page.

image.png

In the top left corner, select File - New - Playground...

image.png

The screenshot below will appear. Choose the default iOS - Blank option.

image.png

Click Next, and you will see the location to store the code. The project file has the .playground extension, which is simple.

Testing the Demo Code#

image.png

Click Run in the image to see the result of running this code.

You can copy the code I provided and test it yourself.

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)%")

What's Next?#

Study the Official Documentation#

The official documentation provides information about UIDevice.current.batteryLevel.

The path is: App and environment - UIDevice - Getting the device battery state - batteryLevel.

batteryLevel | Apple Developer Documentation

Ask AI about Dark Mode and Other Questions#

Ask AI:

How can I use Swift and UIKit to check the current system theme, whether it is in dark mode? I want to wrap it in a function that returns whether it is light or dark, and are there any other values?

I have tested it, and it works. Readers can test it themselves. You can consciously accumulate code and use it later.

Learn about UTS Plugin Wrapping#

[[Beginner's Guide: Wrapping UTS Plugins]]

Learn How to Quickly Test Code in Android#

[[How to Quickly Learn and Test Android Kotlin Code?]]

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