How to add column to Sqlite.swift - sqlite.swift

let tango_id = Expression<Int64>("tango_id")
let e_score = Expression<Double>("e_score")
let interval = Expression<Double>("interval")
let next_revision_date = Expression<Date>("next_revision_date")
let bookmark = Expression<Bool>("bookmark")
let bookmark_date = Expression<Date>("bookmark_date")
let learnt = Expression<Bool>("learnt")
do {
try userdb.run(userTable.create { t in
t.column(tango_id, primaryKey: true)
t.column(e_score)
t.column(interval)
t.column(next_revision_date)
t.column(bookmark)
t.column(learnt)
})
}
catch let error {
print("creation failed: \(error)")
}
I want to add a column for bookmark_date which is defined as Expression

Related

FetchRequest Sorted

Ooookay...
Maybe it's just too late... but I can not get this thing to work.
Actually the fetch ist working... but it's not sorted in any way !?
"zaehler" is an Int32 attribute- should work perfect !?
What am I doing wrong ?
static func getAllMaterialSorted() -> [MaterialMO] {
var result = [MaterialMO]()
let moc = AppDelegate.managedObjectContext
let fetchRequest: NSFetchRequest<MaterialMO> = MaterialMO.fetchRequest()
let zaehler = NSSortDescriptor(key: "zaehler", ascending: false)
let name = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [zaehler]
do {
result = try moc!.fetch(MaterialMO.fetchRequest()) as! [MaterialMO]
} catch {
print ("Cannot fetch employees.Error \(error)")
return result
}
return result
}

How to use thousand separator swift

func showNumbers(){
if let inputString = numberInput.text {
let input = Int(inputString)
let nums = input?.formattedWithSeparator
let group = Int(round(groupslider.value))
let priceEach = Int(round(Double((nums)!/group*100))/100)
perperson.text = String(priceEach)
}
}
}
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
I have two places that I want to make it like 1,000,000
input String and perperson.text
what should I use? NSNumberForatter?
I want to use thousandSeparator or groupSeparator.
I get " Binary operator '/' cannot be applied to operands of type 'String' and 'Int' " this error message.

fatal : Array index out of range

Every child has a pick up point location consists of latitude and longitude that i fetch from sqlite database. I have childIdArray which is array of childID's. I want to calculate the estimate time(ETA) from current location of their respective drivers location i fetch from getCurrentLocationOfRespectiveDrivers() method with pickUp point of children that i fetch from sqlite database in form of array of latitude and longitude.
but i get error
fatal error: Array index out of range
in getCurrentLocationOfRespectiveDrivers() method.
Any help would be highly appreciated.. thanks in advance
var etaArray : [String] = []
var estimatedTime : String?
var latitudeArray : [Double] = []
var longitudeArray : [Double] = []
override func viewDidLoad() {
super.viewDidLoad()
let rs = ModelManager.sharedInstance.fetchingPickUpAnnotationsArray(ChildDetailsVC.parentID)
latitudeArray = rs.latPickUp
longitudeArray = rs.longPickUp
print("pickUpLatitudeArray = \(latitudeArray)")
print("pickUpLongitudeArray = \(longitudeArray)")
let result = ModelManager.sharedInstance.fetchingChildren( ChildDetailsVC.parentID)
self.childNameArray = result.childNames
self.childImageArray = result.childImages
self.childIDArray = result.chidIDs
self.childDriverArray = result.childDrivers
getCurrentLocationOfRespectiveDrivers()
for (var i = 0; i < childIDArray.count; i++)
{
etaArray.append("")
}
}
func getCurrentLocationOfRespectiveDrivers()
{
for( var i = 0 ; i < latitudeArray.count ; i++)
{
let url:NSURL = NSURL(string:"http://development.ssntpl.com/gogo_app/api.php?action=getDriverCurrentLocation")!
let request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
let post:NSString = "child_id=\(childIDArray)"
request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil
{
print("error is \(error)")
return;
}
do
{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = myJSON
{
let Status = parseJSON["status"] as! Int
let Code = parseJSON["code"] as! Int
if (Status == 1 && Code == 200)
{
let Result = parseJSON["result"] as! NSArray
self.etaArray.removeAll()
//here i get the crash fatal error: Array index out of range
let latitudePickUp = self.latitudeArray[i]
let longitudePickUp = self.longitudeArray[i]
let CoordinatePickUp = CLLocation(latitude: latitudePickUp, longitude: longitudePickUp)
for res in Result
{
self.estimatedTime = ""
if (res["exists"] as! Int == 1)
{
let lastLatitude = res["latitude"] as! CLLocationDegrees
let lastLongitude = res["longitude"] as! CLLocationDegrees
let Location : CLLocation = CLLocation(latitude: lastLatitude, longitude: lastLongitude)
let meters:CLLocationDistance = Location.distanceFromLocation(CoordinatePickUp)
print(meters)
let ID = res["child_id"] as! String
let time = round(meters/40000 * 60)
self.estimatedTime = String(time)
self.etaArray.append(self.estimatedTime!)
}
else
{
self.etaArray.append("")
}
}
}
else
{
}
}
}
catch
{
print(error)
}
}
//executing the task
task.resume()
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}

Different ways of adding items to a dictionary with different results

I'm dabbling in swift after a long time away and I've hit an issue that I can't figure out. I'm trying two different ways to add items to a dictionary and getting some different results.
I was initially adding values to a dictionary by doing:
userInfo = ["username":username]
userInfo = ["email":email]
userInfo = ["password":password]
I would then print("\(userInfo)") but it would only contain password.
I then tried switching it up to:
userInfo!["username"] = username
userInfo!["email"] = email
userInfo!["password"] = password
but this resulted in fatal error: unexpectedly found nil while unwrapping an Optional value for username
I finally switched it to the following configuration
userInfo = ["username":username]
userInfo!["email"] = email
userInfo!["password"] = password
and everything prints put. Whats up with that?
Full implementation:
nextPressed()
{
if let userInfo:[String:String] = try registrationValidation()
{
print("\(userInfo)")
}
}
func registrationValidation () throws -> [String:String]?
{
var userInfo: [String:String]?
var problems: [ValidationMessage] = []
if let username = usernameField.text
{
let p1 = validateUsername(username)
problems.appendContentsOf(p1)
userInfo = ["username":username]
//userInfo!["username"] = username
//Above results in nil, yet lines below work?
}
if let email = emailField.text
{
let p2 = validateEmail(email)
problems.appendContentsOf(p2)
//userInfo = ["email":email]
userInfo!["email"] = email
}
if let password = passwordField.text
{
let p3 = validatePassword(password)
problems.appendContentsOf(p3)
//userInfo = ["password":password]
userInfo!["password"] = password
}
if !problems.isEmpty{
throw ValidationError(problems:problems)
}
else
{
print("validation succeeded")
return userInfo
}
}
I think this would be a better way to do what you want to achieve like :
func registrationValidation () throws -> [String:String]?
{
var userInfo = [String:String]() // **Initialize an empty dictionary**
var problems: [ValidationMessage] = []
if let username = usernameField.text
{
let p1 = validateUsername(username)
problems.appendContentsOf(p1)
userInfo["username"] = username
}
if let email = emailField.text
{
let p2 = validateEmail(email)
problems.appendContentsOf(p2)
//userInfo = ["email":email] **// This line will result in creating a new dictionary object**
userInfo["email"] = email
}
if let password = passwordField.text
{
let p3 = validatePassword(password)
problems.appendContentsOf(p3)
//userInfo = ["password":password]
userInfo["password"] = password
}
if !problems.isEmpty{
throw ValidationError(problems:problems)
}
else
{
print("validation succeeded")
return userInfo
}
}

Returning from a function in a closure

I need to get an array of events for a certain day in Swift. Because EKEventStore.requestAccessToEntityType is run asynchronously, I am using dispatch_group_notify to wait for the completion handler of EKEventStore.requestAccessToEntityType to complete so I can do something with it then return it. But I can't return from the function inside the closure I pass to dispatch_group_notify because it tries the return from the closure, not the function. Here is my code
class func eventsOn(date: NSDate) -> [Event] {
var events = [Event]()
var ekEvents = [EKEvent]()
var dispatch_group = dispatch_group_create()
dispatch_group_enter(dispatch_group)
Event.eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {
gotAccess, error in
let cal = NSCalendar.currentCalendar()
var comps = cal.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date)
let aFewHoursAgo = NSDateComponents()
aFewHoursAgo.hour = -5
var daStartDate = cal.dateFromComponents(comps)!
daStartDate = cal.dateByAddingComponents(aFewHoursAgo, toDate: daStartDate, options: .allZeros)!
var aDay = NSDateComponents()
aDay.day = 1
var daEndDate = cal.dateByAddingComponents(aDay, toDate: daStartDate, options: .allZeros)!
daEndDate = daEndDate.dateByAddingTimeInterval(-1)!
let p = Event.eventStore.predicateForEventsWithStartDate(daStartDate, endDate: daEndDate, calendars: [Event.eventStore.defaultCalendarForNewEvents])
let tmp = Event.eventStore.eventsMatchingPredicate(p) as [EKEvent]?
if let _ = tmp {
ekEvents = tmp!
}
dispatch_group_leave(dispatch_group)
})
let queue = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)
dispatch_group_notify(dispatch_group, queue) {
println(ekEvents)
let ekEventId = Expression<String>("ekEventId")
let eventId = Expression<Int>("id")
for ekEvent in ekEvents {
let daEventId = Event.db["events"].filter(ekEventId == ekEvent.eventIdentifier).select(eventId).first![eventId]
events.append(Event.eventWithId(daEventId)!)
}
return events
}
}
So where I put return events inside of the block I passed to dispatch_group_notify it tries to return from the closure, but I'd like to return from the function. How can I do this?

Resources