Skip to main content

I had an instance where I needed to move content from a plist to the server database.  To achieve this step, I added a few lines of code where the plist was called and added a call to the API so the data would be on the server.

The original code appeared as:

class ContactsSource {
  static var contacts: [Contact] {
    let data = try! PlistLoader.array(fromFile: "ContactsDB", ofType: "plist")
    return data.compactMap { Contact(dictionary: $0) }
  }
}

I needed to access the data.compactMap output and have that in an a for loop.  In total there were just a smidge over 500 records.  These were added within a few seconds.  The final code was:

class ContactsSource {
  static var contacts: [Contact] {
    let data = try! PlistLoader.array(fromFile: "ContactsDB", ofType: "plist")
    let dataMap = data.compactMap { Contact(dictionary: $0) }
    for item in dataMap {
      let user = item.firstName.lowercased()
      let pass = "\(user);12"
      RealmPersons().setupRegisterAPI(name: user, pass: pass, mail: item.email, status: "1", timezone: "Australia/Melbourne", firstname: item.firstName, lastname: item.lastName, nickname: item.firstName, mobile: item.phone, avatarname: item.imageName)
    }
    return dataMap
  }
}

I wasn't concerned about the passwords being extremely weak.  As they will be overridden shortly later in a cron on the server.  I was wanting to keep the code here clean and efficient.

For those who reached out about the weak password and I really need to have something more robust... you can add this function.

// random alphanumeric string generator

func randomString(length: Int) -> String {
  let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:;<>!@#$%^&*()"
  return String((0..<length).map{ _ in letters.randomElement()! })
}

Subsequently, update the pass variable from 

let pass = "\(user);12" 

and make it 

let pass = randomString(length: 12)