Basic Adding - Expression was too complex error (Swift) - swift

Trying to add some simple numbers together. Get the "Expression was too complex to be solved in a reasonable time..." error on the final line. Why? Surely it can't come much simpler?
let year = calendar.component(.CalendarUnitYear, fromDate: inputGregorianDate)
let month = calendar.component(.CalendarUnitMonth, fromDate: inputGregorianDate)
let day = calendar.component(.CalendarUnitDay, fromDate: inputGregorianDate)
// Conversion Calulation
let AGR = year/100
let BGR = AGR/4
let CGR = 2 - AGR + BGR
var EGR = 0.00
if (month <= 2 ) {
EGR = 365.25 * Double(year + 4716)
} else {
EGR = 365.25 * Double(year + 4716);
}
let FGR = 30.6001 * Double(month + 1);
let dateJulian = Double(CGR + day + EGR + FGR - 1524.5)

// Conversion Calulation
let AGR = Double(year) / 100
let BGR = AGR / 4.0
let CGR = 2.0 - AGR + BGR
var EGR = 0.0
// this conditional doesn't make any sense
if (month <= 2 ) {
EGR = 365.25 * Double(year + 4716)
} else {
EGR = 365.25 * Double(year + 4716)
}
let FGR = 30.6001 * Double(month + 1)
let dateJulian = CGR + Double(day) + EGR + FGR - 1524.5

Related

The compiler is unable to type-check this expression

I want to divide difference data into 60 and print it as double numbers. When I print it as a string, it does not appear to be a fraction of the number. I get this problem when I print the number "n" . What should I do?
My mistake: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
if let date = formatter.date(from: receivedTimeString) {
let receivedTimeHoursMinutes = Calendar.current.component(.hour, from: date) * 60
let receivedTimeMinutes = Calendar.current.component(.minute, from: date)
let totalreceivedTimeMinutes = receivedTimeHoursMinutes + receivedTimeMinutes
let todayHoursMinutes = Calendar.current.component(.hour, from: Date()) * 60
let todayMinutes = Calendar.current.component(.minute, from: Date())
let todayTimeMinutes = todayHoursMinutes + todayMinutes
let difference = todayTimeMinutes - totalreceivedTimeMinutes
let str = String(difference)
switch true {
case difference > 60:
let deger = String(difference / 60)
guard let n = NumberFormatter().number(from: deger) else { return }
print("deger", deger)
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Saattir") + (" ") + (durum)
case difference == 0:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
case difference < 60:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
default:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
}
If i had understood your question correctly,
If you want to have result of following code as decimal fraction,
let deger = String(difference / 60) // Dividing by INT will not give fractions.
Change it to following.
let deger = String(difference / 60.0)

Calculate average pace

I need to convert a decimal hour in to hh:mm:ss to display as average pace for a walking app.
I have converted the time to decimal and I have calculated the pace in to decimal however I am unsure how to convert this to time.
My timeDecimal is:
let timeDecimal:Double = (hourSource + (minuteSource / 60) + (secondSource / 3600)) / distanceSource
which gives me something like 0.4375
0 = 0
.4375 * 60 = 26.25
.25 = * 60 = 15
I know the time should be 00:26:15 but not sure the formula to achieve this without splitting up the result and performing the multiplication multiple times.
Any help is appreciated.
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [ .Hour, .Minute, .Second ]
formatter.unitsStyle = .Positional
formatter.zeroFormattingBehavior = .Pad
let string = formatter.stringFromTimeInterval(0.4375 * 3600)!
Result: 0:26:15.
Try
var mytime = timeDecimal * 60
var minutes = floor(mytime)
var seconds = (mytime - minutes) * 60
func timeStringFrom(time time: Int) -> String {
let HoursLeft = time/3600
let MinutesLeft = (time%3600)/60
let SecondsLeft = (((time%3600)%60)%60)
if HoursLeft == 0 {
return String(format:"%.2d:%.2d", MinutesLeft, SecondsLeft)
} else {
return String(format:"%2d:%.2d:%.2d", HoursLeft, MinutesLeft, SecondsLeft)
}
}
Note: I'll probably turn it into a generic function soon

Subtracting inputed data in Swift

Good afternoon,
I am having an issue trying to figure out how I take data that was inputed from a textfield and use that data later on in the code. I have attached my code and hopefully I would be able to get some help.
#IBAction func wEnter(sender: AnyObject) {
let number1 = Double(waistText1?.text ?? "") ?? 0
let number2 = Double(waistText2?.text ?? "") ?? 0
let number3 = Double(waistText3?.text ?? "") ?? 0
let number4 = Double(neckText1?.text ?? "") ?? 0
let number5 = Double(neckText2?.text ?? "") ?? 0
let number6 = Double(neckText3?.text ?? "") ?? 0
wavgText.text = String(round(10 * (number1 + number2 + number3) / 3) / 10 ) + " inches"
navgText.text = String((number4 + number5 + number6) / 3) + " inches"
let number7 = Double(wavgText.text! )
let number8 = Double(navgText.text! )
soldBF.text = String(number7 - number8) + "%"
}
Everything seems to be working correctly except for when i try to subtract number7 from number 8. Am i missing something?
if you need anymore details please let me know
It will be better if you switch the order of operations:
let number7 = round(10 * (number1 + number2 + number3) / 3) / 10
let number8 = (number4 + number5 + number6) / 3
wavgText.text = "\(number7) inches"
navgText.text = "\(number8) inches"
soldBF.text = "\(number7 - number8)%"
Then you can see what the problem is.

Using NSDate to get date for Easter

I'm working on an application that requires the use of getting dates for national holidays.
Below, I was able to get Memorial Day:
// Set the components for Memorial Day (last Monday of May)
let memorialDayComps = NSDateComponents()
memorialDayComps.weekday = 2
memorialDayComps.month = 5
memorialDayComps.year = currentYear
var mondaysOfMay = [NSDate]()
for var i = 1; i <= 5; i++ {
memorialDayComps.weekdayOrdinal = i
let monday = calendar.dateFromComponents(memorialDayComps)
let components = calendar.components(.CalendarUnitMonth, fromDate: monday!)
if components.month == 5 {
mondaysOfMay.append(monday!)
}
}
let memorialDayDate = mondaysOfMay.last
Because the dates are pretty well set, I am able to successfully create NSDate instances for the following holidays:
New Year's Day
Martin Luther King, Jr. Day
Presidents' Day
Memorial Day
Independence Day
Labor Day
Thanksgiving Day
Christmas Day
However, the only one that I am having difficulty figuring out how to get is Easter. It varies every year, so I'm curious as to whether anyone else has been able so successfully get the date for Easter via an API or other means.
I was able to find a gist on GitHub that has a solution that was accurate for calculating and returning an NSDate for Easter.
The code below is what the gist contains:
// Easter calculation in swift after Anonymous Gregorian algorithm
// Also known as Meeus/Jones/Butcher algorithm
func easter(Y : Int) -> NSDate {
let a = Y % 19
let b = Int(floor(Double(Y) / 100))
let c = Y % 100
let d = Int(floor(Double(b) / 4))
let e = b % 4
let f = Int(floor(Double(b+8) / 25))
let g = Int(floor(Double(b-f+1) / 3))
let h = (19*a + b - d - g + 15) % 30
let i = Int(floor(Double(c) / 4))
let k = c % 4
let L = (32 + 2*e + 2*i - h - k) % 7
let m = Int(floor(Double(a + 11*h + 22*L) / 451))
let components = NSDateComponents()
components.year = Y
components.month = Int(floor(Double(h + L - 7*m + 114) / 31))
components.day = ((h + L - 7*m + 114) % 31) + 1
components.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)
return cal.dateFromComponents(components)
}
println(easter(2014)) // "2014-04-20 00:00:00 +0000"
That Easter algorithm works great!
Using with Swift 4.0 and pattern matching. Pattern matching made it easier for me to add other days based on month, day, weekday, weekdayOrdinal.
extension Date {
var isUSHoliday: Bool {
let components = Calendar.current.dateComponents([.year, .month, .day, .weekday, .weekdayOrdinal], from: self)
guard let year = components.year,
let month = components.month,
let day = components.day,
let weekday = components.weekday,
let weekdayOrdinal = components.weekdayOrdinal else { return false }
let easterDateComponents = Date.dateComponentsForEaster(year: year)
let easterMonth: Int = easterDateComponents?.month ?? -1
let easterDay: Int = easterDateComponents?.day ?? -1
let memorialDay = Date.dateComponentsForMemorialDay(year: year)?.day ?? -1
// weekday is Sunday==1 ... Saturday==7
// weekdayOrdinal is nth instance of weekday in month
switch (month, day, weekday, weekdayOrdinal) {
case (1, 1, _, _): return true // Happy New Years
case (1, 0, 2, 3): return true // MLK - 3rd Mon in Jan
case (2, 0, 2, 3): return true // Washington - 3rd Mon in Feb
case (easterMonth, easterDay, _, _): return true // Easter - rocket science calculation
case (5, memorialDay, _, _): return true // Memorial Day
case (7, 4, _, _): return true // Independence Day
case (9, 0, 2, 1): return true // Labor Day - 1st Mon in Sept
case (10, 0, 2, 2): return true // Columbus Day - 2nd Mon in Oct
case (11, 11, _, _): return true // Veterans Day
case (11, 0, 5, 4): return true // Happy Thanksgiving - 4th Thurs in Nov
case (12, 25, _, _): return true // Happy Holidays
case (12, 31, _, _): return true // New years Eve
default: return false
}
}
static func dateComponentsForMemorialDay(year: Int) -> DateComponents? {
guard let memorialDay = Date.memorialDay(year: year) else { return nil }
return NSCalendar.current.dateComponents([.year, .month, .day, .weekday, .weekdayOrdinal], from: memorialDay)
}
static func memorialDay(year: Int) -> Date? {
let calendar = Calendar.current
var firstMondayJune = DateComponents()
firstMondayJune.month = 6
firstMondayJune.weekdayOrdinal = 1 // 1st in month
firstMondayJune.weekday = 2 // Monday
firstMondayJune.year = year
guard let refDate = calendar.date(from: firstMondayJune) else { return nil }
var timeMachine = DateComponents()
timeMachine.weekOfMonth = -1
return calendar.date(byAdding: timeMachine, to: refDate)
}
static func easterHoliday(year: Int) -> Date? {
guard let dateComponents = Date.dateComponentsForEaster(year: year) else { return nil }
return Calendar.current.date(from: dateComponents)
}
static func dateComponentsForEaster(year: Int) -> DateComponents? {
// Easter calculation from Anonymous Gregorian algorithm
// AKA Meeus/Jones/Butcher algorithm
let a = year % 19
let b = Int(floor(Double(year) / 100))
let c = year % 100
let d = Int(floor(Double(b) / 4))
let e = b % 4
let f = Int(floor(Double(b+8) / 25))
let g = Int(floor(Double(b-f+1) / 3))
let h = (19*a + b - d - g + 15) % 30
let i = Int(floor(Double(c) / 4))
let k = c % 4
let L = (32 + 2*e + 2*i - h - k) % 7
let m = Int(floor(Double(a + 11*h + 22*L) / 451))
var dateComponents = DateComponents()
dateComponents.month = Int(floor(Double(h + L - 7*m + 114) / 31))
dateComponents.day = ((h + L - 7*m + 114) % 31) + 1
dateComponents.year = year
guard let easter = Calendar.current.date(from: dateComponents) else { return nil } // Convert to calculate weekday, weekdayOrdinal
return Calendar.current.dateComponents([.year, .month, .day, .weekday, .weekdayOrdinal], from: easter)
}
}
Here is a Swift 5 implementation of O'Beirne's algorithm with inline documentation.
The code is more compact than the implementations in the other provided answers because it makes use of Integer arithmetic and thus removes the need to explicitly round numbers and convert between Floats and Ints.
/// **How ten divisions lead to Easter** *by T. H. O'Beirne, New Scientist, march 30 1961 - Vol. 9,Nr. 228*
func easter(in year: Int) -> (day: Int, month: Int) {
/// Identify the position of the `year` in a 19-year cycle, to use this later to determine the principal constituent of the changes of full-moon dates from year to year
let a = year % 19
/// Take note of the corrections which the Gregorian calendar introduces in century years
let (b, c) = year.quotientAndRemainder(dividingBy: 100)
/// Take account of the leap-year exceptions in century years
let (d, e) = b.quotientAndRemainder(dividingBy: 4)
/// Provide similarly for the century years auxiliary corrections to the new-moon and full-moon dates
let g = (8*b + 13) / 25
/// Determine the number of days between 21 March and the coincident or next full moon, if no special exceptions arise
let h = (19*a + b - d - g + 15) % 30
/// Determine the position of the year in the ordinary leap-year cycle of four years
let (i, k) = c.quotientAndRemainder(dividingBy: 4)
/// Determine number of days (between 0 and 6) until the Sunday *after* full moon
let l = (2*e + 2*i - h - k + 32) % 7
/// The exceptions which make a 29-day month interrupt the regularity of a simpler pattern need here be considered *only* when they transfer the full moon *from a Sunday to a Saturday*: the *Easter date* is unaffected in other cases. When appropriate — 1954 and 1981 are quite rare examples — we have m=1; otherwise m=0 : this permits the necessary correction (failing which the Easter date *would* be 26 April in 1981.
let m = (a + 11*h + 19*l) / 433
/// Determine days between March 22 and Easter
let relativeDayCount = h + l - 7*m
/// Convert relative day count into absolute month and day index
let month = (relativeDayCount + 90) / 25
return (day: (relativeDayCount + 33*month + 19) % 32, month)
}
func easterDate(in year: Int) -> Date {
let (day, month) = easter(in: year)
let components = DateComponents(
timeZone: TimeZone(secondsFromGMT: 0),
year: year, month: month, day: day
)
return Calendar(identifier: .gregorian).date(from: components)!
}
Swift 4:
func easter(Y : Int) -> Date {
let a = Y % 19
let b = Int(floor(Double(Y) / 100))
let c = Y % 100
let d = Int(floor(Double(b) / 4))
let e = b % 4
let f = Int(floor(Double(b+8) / 25))
let g = Int(floor(Double(b-f+1) / 3))
let h = (19*a + b - d - g + 15) % 30
let i = Int(floor(Double(c) / 4))
let k = c % 4
let L = (32 + 2*e + 2*i - h - k) % 7
let m = Int(floor(Double(a + 11*h + 22*L) / 451))
var components = DateComponents()
components.year = Y
components.month = Int(floor(Double(h + L - 7*m + 114) / 31))
components.day = ((h + L - 7*m + 114) % 31) + 1
components.timeZone = TimeZone(secondsFromGMT: 0)
return Calendar.autoupdatingCurrent.date(from: components)!
}
print(easter(Y: 2018)) // "2018-04-01 00:00:00 +0000"
OBJECTIVE-C!
-(void) easterMonthAndDayForYear: (NSInteger) Y {
NSInteger a = Y % 19;
NSInteger b = (int) (floor( ((double)Y) / 100.0));
NSInteger c = Y % 100;
NSInteger d = (int)(floor(((double)b) / 4.0));
NSInteger e = b % 4;
NSInteger f = (int)(floor(((double)(b+8)) / 25.0));
NSInteger g = (int)(floor(((double)(b-f+1)) / 3.0));
NSInteger h = (19*a + b - d - g + 15) % 30;
NSInteger i = (int)(floor(((double)c) / 4.0));
NSInteger k = c % 4;
NSInteger L = (32 + 2*e + 2*i - h - k) % 7;
NSInteger m = (int)(floor(((double)(a + 11*h + 22*L)) / 451.0));
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |NSCalendarUnitTimeZone fromDate:[NSDate date]];
components.year = Y;
components.month = (int)(floor((double)(h + L - 7*m + 114) / 31.0));
components.day = ((h + L - 7*m + 114) % 31) + 1;
components.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
self.easterDayCache[#(Y)] = #{#"month": #(components.month), #"day":#(components.day)
};

Swift Convert decimal coordinate into degrees, minutes, seconds, direction

How can I covert this to swift? My best guess is that all the int get changed to a var. Removing all the # that lead ". Also if any can point me to a good source to learn how things convert that would great.
- (NSString*)coordinateString {
int latSeconds = (int)(self.latitude * 3600);
int latDegrees = latSeconds / 3600;
latSeconds = ABS(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;
int longSeconds = (int)(self.longitude * 3600);
int longDegrees = longSeconds / 3600;
longSeconds = ABS(longSeconds % 3600);
int longMinutes = longSeconds / 60;
longSeconds %= 60;
NSString* result = [NSString stringWithFormat:#"%d°%d'%d\"%# %d°%d'%d\"%#",
ABS(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? #"N" : #"S",
ABS(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? #"E" : #"W"];
return result;
}
My attempt to convert it but Xcode proves me wrong. Reposted the fix suggest with the ABS. Does it look correct now?
func coordinateString {
var latSeconds = (Int8)(self.latitude * 3600);
var latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
var latMinutes = latSeconds / 60;
latSeconds %= 60;
var longSeconds = (Int8)(self.longitude * 3600);
var longDegrees = longSeconds / 3600;
longSeconds = abs(longSeconds % 3600);
var longMinutes = longSeconds / 60;
longSeconds %= 60;
var result = (String(format: "%d°%d'%d\"%# %d°%d'%d\"%#"),
abs(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? "N" : "S",
abs(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? "E" : "W",
return result;
}
Xcode 12 • Swift 5 or later
extension BinaryFloatingPoint {
var dms: (degrees: Int, minutes: Int, seconds: Int) {
var seconds = Int(self * 3600)
let degrees = seconds / 3600
seconds = abs(seconds % 3600)
return (degrees, seconds / 60, seconds % 60)
}
}
extension CLLocation {
var dms: String { latitude + " " + longitude }
var latitude: String {
let (degrees, minutes, seconds) = coordinate.latitude.dms
return String(format: "%d°%d'%d\"%#", abs(degrees), minutes, seconds, degrees >= 0 ? "N" : "S")
}
var longitude: String {
let (degrees, minutes, seconds) = coordinate.longitude.dms
return String(format: "%d°%d'%d\"%#", abs(degrees), minutes, seconds, degrees >= 0 ? "E" : "W")
}
}
let latitude = -22.9133950
let longitude = -43.2007100
let location = CLLocation(latitude: latitude, longitude: longitude)
location.latitude // "22°54'48"S"
location.longitude // "43°12'2"W"
location.dms // "22°54'48"S 43°12'2"W"
I have just edited Leo Dabus answer to get those String as separate values. In case it is helpful for others:
Swift 3 and Swift 4
func getLocationDegreesFrom(latitude: Double) -> String {
var latSeconds = Int(latitude * 3600)
let latDegrees = latSeconds / 3600
latSeconds = abs(latSeconds % 3600)
let latMinutes = latSeconds / 60
latSeconds %= 60
return String(
format: "%d°%d'%d\"%#",
abs(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? "N" : "S"
)
}
func getLocationDegreesFrom(longitude: Double) -> String {
var longSeconds = Int(longitude * 3600)
let longDegrees = longSeconds / 3600
longSeconds = abs(longSeconds % 3600)
let longMinutes = longSeconds / 60
longSeconds %= 60
return String(
format: "%d°%d'%d\"%#",
abs(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? "E" : "W"
)
}
I took the code of Leo Dabus and fixed a bug related with the detection of the cardinal directions when the values of the latitude or longitude are less than zero, I mean when we are at southern hemisphere or west of the prime meridian.
We can't represent a negative zero with Swift, so we lose the negative sign at the following expression:
let latDegrees = latSeconds / 3600
this bug also makes the expresion:
latDegrees >= 0 ? "N" : "S"
always return N (North) and never S (South).
Here is my version of the code (Swift 5 and Xcode 10):
func coordinate() -> (latitude: String, longitude: String) {
// This function converts from DD (decimal degrees) to DMS (degrees, minutes and seconds)
// Calculating the degrees, minutes and seconds for the given latitude value (DD)
var latitudeSeconds = latitude * 3600
let latitudeDegrees = latitudeSeconds / 3600
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 3600)
let latitudeMinutes = latitudeSeconds / 60
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 60)
// Calculating the degrees, minutes and seconds for the given longitude value (DD)
var longitudeSeconds = longitude * 3600
let longitudeDegrees = longitudeSeconds / 3600
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 3600)
let longitudeMinutes = longitudeSeconds / 60
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 60)
// Analyzing if it's North or South. (Latitude)
let latitudeCardinalDirection = latitudeDegrees >= 0 ? "N" : "S"
// Analyzing if it's East or West. (Longitude)
let longitudeCardinalDirection = longitudeDegrees >= 0 ? "E" : "W"
// Final strings with format <degrees>°<minutes>'<seconds>"<cardinal direction>
let latitudeDescription = String(format:"%.2f°%.2f'%.2f\"%#",
abs(latitudeDegrees), abs(latitudeMinutes),
abs(latitudeSeconds), latitudeCardinalDirection)
let longitudeDescription = String(format:"%.2f°%.2f'%.2f\"%#",
abs(longitudeDegrees), abs(longitudeMinutes),
abs(longitudeSeconds), longitudeCardinalDirection)
return (latitudeDescription, longitudeDescription)
} // coordinate
I also chose to work with Double in order to handle the precision, for example, I prefer to show two decimal places.
The screen output of this code would be something like:
0.17°10.34'20.53"S 78.48°28.59'35.52"W
Based on David Seek and Josué V. Herrera code
func latlon2DMS(latitude: Double) -> String {
var latitudeSeconds = latitude * 3600
let latitudeDegrees = latitudeSeconds / 3600
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 3600)
let latitudeMinutes = latitudeSeconds / 60
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 60)
let latitudeCardinalDirection = latitudeDegrees >= 0 ? "N" : "S"
let latitudeDescription = String(format: "%.2f° %.2f' %.2f\" %#",
abs(latitudeDegrees), abs(latitudeMinutes),
abs(latitudeSeconds), latitudeCardinalDirection)
return latitudeDescription
}
func latlon2DMS(longitude: Double) -> String {
var longitudeSeconds = longitude * 3600
let longitudeDegrees = longitudeSeconds / 3600
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 3600)
let longitudeMinutes = longitudeSeconds / 60
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 60)
let longitudeCardinalDirection = longitudeDegrees >= 0 ? "E" : "W"
let longitudeDescription = String(format: "%.2f° %.2f' %.2f\" %#",
abs(longitudeDegrees), abs(longitudeMinutes),
abs(longitudeSeconds), longitudeCardinalDirection)
return longitudeDescription
}
Call to it with
print(latlon2DMS(latitude: coordLat))
print(latlon2DMS(longitude: coordLong))
latitude.text = latlon2DMS(latitude: coordLat)
longitude.text = latlon2DMS(longitude: coordLong)
I slightly modified Josue V.'s code to work in a timer that updates the location frequently
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways){
let currentLocation = locationManager.location
var latitudeSeconds = currentLocation!.coordinate.latitude * 3600
let latitudeDegrees = latitudeSeconds / 3600
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 3600)
let latitudeMinutes = latitudeSeconds / 60
latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 60)
var longitudeSeconds = currentLocation!.coordinate.longitude * 3600
let longitudeDegrees = longitudeSeconds / 3600
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 3600)
let longitudeMinutes = longitudeSeconds / 60
longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 60)
let latitudeCardinalDirection = latitudeDegrees >= 0 ? "N" : "S"
let longitudeCardinalDirection = longitudeDegrees >= 0 ? "E" : "W"
let latitudeDescription = String(format:"%.2f°%.2f'%.2f\"%#",
abs(latitudeDegrees), abs(latitudeMinutes),
abs(latitudeSeconds), latitudeCardinalDirection)
let longitudeDescription = String(format:"%.2f°%.2f'%.2f\"%#",
abs(longitudeDegrees), abs(longitudeMinutes),
abs(longitudeSeconds), longitudeCardinalDirection)
cell5.text = latitudeDescription + " " + longitudeDescription
}
}
and the timer
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(coordinate), userInfo: nil, repeats: true)