辛宝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 into 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 a response. 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. Please also be aware of this as a reader.

Where does the code come from?#

In the past, 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 to quickly learn UIKit and Swift?

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

The following solutions are based on Xcode 15.4. With version iterations, 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 dialog box below.

image.png

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

Click Next to get the dialog box below.

image.png

Tips:

  • Enter any name for Product Name.
  • Select any option for Team. I chose None.
  • The Org ID can be left as default or in the format of a.b.c.
  • For Interface, I tried selecting Storyboard and not selecting SwiftUI.
  • Select Swift for Language.
  • Select None for Storage.
  • Deselect Include Tests.

Click Next, and the following popup will appear, allowing you to choose the code storage path.

image.png

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

Testing Demo Code#

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

image.png

Following the prompts in my screenshot, open ViewController.swift and delete everything. Then, paste the code I provided:

import UIKit

class ViewController: UIViewController {

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

    func getBatteryLevel() -> Float {
        // Enable battery monitoring
        UIDevice.current.isBatteryMonitoringEnabled = true
        
        // Get 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 a 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 option iOS - Blank.

image.png

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

Testing Demo Code#

image.png

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

You can copy the code I provided to verify it:

import UIKit

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

// Get battery level and print
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 Other Questions, such as Dark Mode#

Ask AI:

How can I use Swift and UIKit to query the current system theme, whether it is dark mode? I want to wrap it into 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.