iPhone에서 최초 앱 실행을 감지하는 방법
최초 출시를 어떻게 감지 할 수 있습니까?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// if very first launch than perform actionA
// else perform actionB
}
방법?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
return YES;
}
에서 스위프트 3, 4는 이 시도 :
func isAppAlreadyLaunchedOnce()->Bool{
let defaults = UserDefaults.standard
if let isAppAlreadyLaunchedOnce = defaults.string(forKey: "isAppAlreadyLaunchedOnce"){
print("App already launched : \(isAppAlreadyLaunchedOnce)")
return true
}else{
defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
return false
}
}
에서 스위프트 2 , 이것을 시도
func isAppAlreadyLaunchedOnce()->Bool{
let defaults = NSUserDefaults.standardUserDefaults()
if let isAppAlreadyLaunchedOnce = defaults.stringForKey("isAppAlreadyLaunchedOnce"){
print("App already launched : \(isAppAlreadyLaunchedOnce)")
return true
}else{
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
return false
}
}
UPDATE : - 들어 OBJ-C I이를 사용,
+ (BOOL)isAppAlreadyLaunchedOnce {
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isAppAlreadyLaunchedOnce"])
{
return true;
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAppAlreadyLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
return false;
}
}
OBJ-C에 대한 참조 : https://stackoverflow.com/a/9964400/3411787
이 목적을 위해 작은 라이브러리를 작성했습니다. 최초 출시인지 아니면이 버전인지, 사용자가 설치 한 이전 버전인지 알려줍니다. github에서 Apache 2 라이센스에 따라 cocoapod로 제공됩니다 : GBVersionTracking
당신은 단지 이것을 호출 application:didFinishLaunching:withOptions:
[GBVersionTracking track];
그리고 이것이 첫 번째 발사인지 확인하려면 어디서나 이것을 호출하십시오.
[GBVersionTracking isFirstLaunchEver];
그리고 비슷하게 :
[GBVersionTracking isFirstLaunchForVersion];
[GBVersionTracking currentVersion];
[GBVersionTracking previousVersion];
[GBVersionTracking versionHistory];
Xcode 7 및 Swift 2.0의 또 다른 아이디어는 확장을 사용하는 것입니다.
extension NSUserDefaults {
func isFirstLaunch() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("HasAtLeastLaunchedOnce") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasAtLeastLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}
이제 앱 어디에서나 쓸 수 있습니다
if NSUserDefaults.standardUserDefaults().isFirstLaunch() {
// do something on first launch
}
개인적으로 다음과 같이 UIApplication 확장을 선호합니다.
extension UIApplication {
class func isFirstLaunch() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("HasAtLeastLaunchedOnce") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasAtLeastLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}
함수 호출이 더 설명하기 때문에 :
if UIApplication.isFirstLaunch() {
// do something on first launch
}
아래 정적 메소드로 구현할 수 있습니다.
+ (BOOL)isFirstTime{
static BOOL flag=NO;
static BOOL result;
if(!flag){
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"hasLaunchedOnce"]){
result=NO;
}else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
result=YES;
}
flag=YES;
}
return result;
}
스위프트 3.0
확장 기능 추가
extension UIApplication {
class func isFirstLaunch() -> Bool {
if UserDefaults.standard.bool(forKey: "hasBeenLaunchedBeforeFlag") {
UserDefaults.standard.set(true, forKey: "hasBeenLaunchedBeforeFlag")
UserDefaults.standard.synchronize()
return true
}
return false
}
}
그런 다음 코드에서
UIApplication.isFirstLaunch()
시작할 때 무언가를 저장 한 다음 존재하는지 확인해야합니다. 그렇지 않다면 처음입니다. "뭔가"는 파일, 데이터베이스 항목, 사용자 기본값 설정 ...이 될 수 있습니다.
이 작업은 매우 간단하며 6 줄의 코드 만 필요합니다.
응용 프로그램 시작 환경 설정 또는 응용 프로그램을 처음 실행했는지 테스트해야 할 다른 곳에이 코드를 추가하는 것이 유용합니다.
//These next six lines of code are the only ones required! The rest is just running code when it's the first time.
//Declare an integer and a default.
NSUserDefaults *theDefaults;
int launchCount;
//Set up the properties for the integer and default.
theDefaults = [NSUserDefaults standardUserDefaults];
launchCount = [theDefaults integerForKey:@"hasRun"] + 1;
[theDefaults setInteger:launchCount forKey:@"hasRun"];
[theDefaults synchronize];
//Log the amount of times the application has been run
NSLog(@"This application has been run %d amount of times", launchCount);
//Test if application is the first time running
if(launchCount == 1) {
//Run your first launch code (Bring user to info/setup screen, etc.)
NSLog(@"This is the first time this application has been run";
}
//Test if it has been run before
if(launchCount >= 2) {
//Run new code if they have opened the app before (Bring user to home screen etc.
NSLog(@"This application has been run before);
}
추신 환경 설정에서 부울을 사용하지 마십시오 정수만 사용하십시오. 정의되지 않은 경우 기본값은 0입니다.
Also, the [theDefaults synchronize]; line isn't required but I've found that when an app is ran hundreds of times across hundreds of devices, the results aren't always reliable, besides, it's better practice.
store a bool key in NSUserDefaults first time it will be no you will change it to yes and keep it like that until the app delete or reinstall it will be again tha first time.
For Swift 2.0 in Xcode 7. In the AppDelegate.swift file:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
{
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
didFinishLaunchingOnce()
return true
}
func didFinishLaunchingOnce() -> Bool
{
let defaults = NSUserDefaults.standardUserDefaults()
if let hasBeenLauncherBefore = defaults.stringForKey("hasAppBeenLaunchedBefore")
{
//print(" N-th time app launched ")
return true
}
else
{
//print(" First time app launched ")
defaults.setBool(true, forKey: "hasAppBeenLaunchedBefore")
return false
}
}
}
Quick and easy function
- (BOOL) isFirstTimeOpening {
NSUserDefaults *theDefaults = [NSUserDefaults standardUserDefaults];
if([theDefaults integerForKey:@"hasRun"] == 0) {
[theDefaults setInteger:1 forKey:@"hasRun"];
[theDefaults synchronize];
return true;
}
return false;
}
swift
struct Pref {
static let keyFirstRun = "PrefFirstRun"
static var isFirstRun: Bool {
get {
return UserDefaults.standard.bool(forKey: keyFirstRun)
}
set {
UserDefaults.standard.set(newValue, forKey: keyFirstRun)
}
}
}
Register default values on app launch:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let prefs: [String:Any] = [
Pref.keyFirstRun: true
...
]
UserDefaults.standard.register(defaults: prefs)
Clear value on app termination:
func applicationWillTerminate(_ application: UIApplication) {
Pref.isFirstRun = false
Check value:
if Pref.isFirstRun {
... do whatever
NSUserDefaults + Macro
The best approach is to use NSUserDefaults and save a BOOL variable. As mentioned above, the following code will do just fine:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSNumber numberWithBool:true] forKey:@"~applicationHasLaunchedBefore"];
[userDefaults synchronize];
You can also create a macro as below to easily check whether it is the first launch or not
#define kApplicationHasLaunchedBefore [[NSUserDefaults standardUserDefaults] objectForKey:@"~applicationHasLaunchedBefore"]
Then use it as such,
if (kApplicationHasLaunchedBefore) {
//App has previously launched
} else {
//App has not previously launched
}
Here is an answer working in swift 5.0. The improvement compared to @Zaid Pathan's answer is that there is no hidden contract. If you don't call setFirstAppLaunch() exactly once before calling isFirstAppLaunch() you'll get an assertion error (only in debug mode).
fileprivate struct _firstAppLaunchStaticData {
static var alreadyCalled = false
static var isFirstAppLaunch = true
static let appAlreadyLaunchedString = "__private__appAlreadyLaunchedOnce"
}
func setFirstAppLaunch() {
assert(_firstAppLaunchStaticData.alreadyCalled == false, "[Error] You called setFirstAppLaunch more than once")
_firstAppLaunchStaticData.alreadyCalled = true
let defaults = UserDefaults.standard
if defaults.string(forKey: _firstAppLaunchStaticData.appAlreadyLaunchedString) != nil {
_firstAppLaunchStaticData.isFirstAppLaunch = false
}
defaults.set(true, forKey: _firstAppLaunchStaticData.appAlreadyLaunchedString)
}
func isFirstAppLaunch() -> Bool {
assert(_firstAppLaunchStaticData.alreadyCalled == true, "[Error] Function setFirstAppLaunch wasn't called")
return _firstAppLaunchStaticData.isFirstAppLaunch
}
Then you just need to call the function setFirstAppLaunch() at the start of your application and isFirstAppLaunch() whenever you want to check if your app has been called.
참고URL : https://stackoverflow.com/questions/9964371/how-to-detect-first-time-app-launch-on-an-iphone
'Programming' 카테고리의 다른 글
| 리스트 변환 (0) | 2020.06.02 |
|---|---|
| PHP-파일을 서버의 다른 폴더로 이동 (0) | 2020.06.02 |
| 트위터 부트 스트랩 모달 : 슬라이드 다운 효과를 제거하는 방법 (0) | 2020.06.02 |
| Intellij IDEA는 for-each / for 키보드 단축키를 생성합니다. (0) | 2020.06.02 |
| HttpContent 사용 방법을 찾을 수 없습니다 (0) | 2020.06.02 |