iOS SDK Static Library development

As a practice, let’s try to develop static library

  1. Create a library project
  2. Write codes
  3. Build static library
  4. Copy static library into another app project
  5. Use library
スポンサーリンク

Create a library project

To create library is simple. Choose “Static Library” from XCode template.

Write codes

MyStaticLibrary.swift

//
//  MyStaticLibrary.swift
//  MyStaticLibrary
//
//  Created by dj110 on 1/5/22.
//

open class MyStaticLibrary {
    
    public init() {}

    public func hello() -> String {
        print("Hello!")
        return "Hello!"
    }
}

Build static library

In this time, just for testing. So, target is simulator and debug build.

Let’s build from XCode menu

Success build. Can see libMyStaticLibrary.a

In my case, the build is under /Developer/XCode/DeriveData/MyStaticLibrary-xxxxxx/Build/Products/Debug-iphonesimulator/libMyStaticLibrary.a
When I go this folder, I can see 1 file and 1 folder.

O.K. Now, it’s ready to use

Copy static library into another app project

Next, create new project for iOS app.

Name is MyStaticLibrarySample

Copy above 2 files under MyStaticLibrarySample/Libraries

Add a module from App TARGETS Link Binary

Import is completed

Use library

Let’s use this library from App.

This function is super simple, just returns fixed text “Hello!”, so change default Swift UI code and show text on the iPhone screen.

ContentView.swift

import SwiftUI
import MyStaticLibrary

struct ContentView: View {
    var body: some View {
        Text(MyStaticLibrary().hello())
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

import MyStaticLibrary

MyStaticLibrary().hello()

Above 2 parts are important code to load from library

Show Hello!, it works

iOS
スポンサーリンク
Professional Programmer2

コメント