How to determine the date an app is installed or used for the first time?

后端 未结 10 575
慢半拍i
慢半拍i 2020-12-03 01:40

I\'m planning on opening up an in app store and I\'d like to give existing users some of the items for free.

I thought of releasing an update which would store some

相关标签:
10条回答
  • App build date:

    public var appBuildDate: Date {
      if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
        if let createdDate = try! FileManager.default.attributesOfItem(atPath: path)[.creationDate] as? Date {
          return createdDate
        }
      }
      return Date() // Should never execute
    }
    

    App installation date:

    public var appInstallDate: Date {
      if let documentsFolder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
        if let installDate = try! FileManager.default.attributesOfItem(atPath: documentsFolder.path)[.creationDate] as? Date {
          return installDate
        }
      }
      return Date() // Should never execute
    }
    
    0 讨论(0)
  • 2020-12-03 02:18

    My solution would be to check the last modified date of one of the files in the app bundle.

    NSString *sourceFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Icon.png"];
    
    NSDate *lastModif = [[[NSFileManager defaultManager] attributesOfItemAtPath:sourceFile error:&err] objectForKey:NSFileModificationDate];
    
    0 讨论(0)
  • 2020-12-03 02:19

    Using the creation date of Documents directory is the best solution so far. Reproducing it in Swift 4.2

    var inferredDateInstalledOn: Date? {
        guard
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last,
            let attributes = try? FileManager.default.attributesOfItem(atPath: documentsURL.path),
            else { return nil }
        return attributes[.creationDate] as? Date
    }
    
    0 讨论(0)
  • 2020-12-03 02:19

    Here's a little safer approach, with out the force try and force unwrapping, and update to suit SWIFT 5:

    if
        let urlToDocumentsFolder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last,
        let installDateAny = (try? FileManager.default.attributesOfItem(atPath: urlToDocumentsFolder.path)[.creationDate]),
        let installDate = installDateAny as? Date
    {
        print("This app was installed by the user on \(installDate)")
    }
    
    0 讨论(0)
提交回复
热议问题