Swift(스위프트): 앱 최초 설치 후 한 번만 실행하는 작업, 버전 업데이트시에만 실행하는 작업 만들기
Swift(스위프트): 앱 최초 설치 후 한 번만 실행하는 작업, 버전 업그레이드시에만 실행하는 작업 만들기
1: 아래 코드를 프로젝트 내에 추가합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Foundation
func checkAppFirstrunOrUpdateStatus(firstrun: () -> (), updated: () -> (), nothingChanged: () -> ()) {
let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let versionOfLastRun = UserDefaults.standard.object(forKey: "VersionOfLastRun") as? String
// print(#function, currentVersion ?? "", versionOfLastRun ?? "")
if versionOfLastRun == nil {
// First start after installing the app
firstrun()
} else if versionOfLastRun != currentVersion {
// App was updated since last run
updated()
} else {
// nothing changed
nothingChanged()
}
UserDefaults.standard.set(currentVersion, forKey: "VersionOfLastRun")
UserDefaults.standard.synchronize()
}
UserDefaults를 이용해서 앱의 버전 변화를 감지합니다.- 앱 설치 후 최초 실행 시
VersionOfLastRun의 키값이nil입니다. - 한 번 실행하면 현재 앱의 버전이
VersionOfLastRun키값에 저장됩니다. - 다시 실행했을 때
VersionOfLastRun의 값에 변화가 없다면 앱이 업데이트 된 적이 없으며 버전이 그대로입니다. - 다시 실행했을 때
VersionOfLastRun의 값에 변화가 있다면 앱스토어 등에서 버전이 업데이트 된 것입니다.
- 앱 설치 후 최초 실행 시
2: 아래 코드를 AppDelegate.swift 파일 내의 func application(…… didFinishLaunchingWithOptions launchOptions: ….) 함수에 추가하고 상황별 각 클로저마다 실핼할 작업을 입력합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// ... //
// 각 상황별로 실행할 작업을 클로저 내에 작성
checkAppFirstrunOrUpdateStatus {
print("앱 설치 후 최초 실행할때만 실행됨")
} updated: {
print("버전 변경시마다 실행됨")
} nothingChanged: {
print("변경 사항 없음")
}
return true
}
}
기존에 빌드된 앱을 삭제한 뒤 재설치합니다. 최초 실행하면 firstrun이 실행됩니다.
[caption id=”attachment_4487” align=”alignnone” width=”553”]
firstrun 클로저는 앱 설치 후 최초 실행시에만 실행되고, 그 이후에는 실행되지 않습니다.[/caption]
이 상태에서 다시 빌드하고 실행하면 nothingChanged가 실행됩니다.
[caption id=”attachment_4488” align=”alignnone” width=”585”]
nothingChanged 클로저는 버전이 변하지 않았을 때 실행됩니다.[/caption]
프로젝트 설정에서 버전을 변경합니다.
[caption id=”attachment_4489” align=”alignnone” width=”596”]
버전 변경 후 다시 실행[/caption]
버전 변경 후 빌드 및 실행하면 버전이 변경되면서 updated가 실행된 것을 알 수 있습니다.
[caption id=”attachment_4490” align=”alignnone” width=”593”]
updated 클로저는 앱 버전이 변경될 때마다 실행됩니다. (버전 업/다운 모두 포함)[/caption]
This post is licensed under
CC BY 4.0
by the author.