fatal : Array index out of range - swift2

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()
})
}

Related

Knowing when to use a Double, String or Int when casting an Array from an API?

I am trying to cast multiple Arrays from a weather API. I was able to get the 5 day highs using a Double, then I was able to match them with the days of the week using a String.
Now I am trying to pull the the 5 days lows and the weather Icons associated to the day and no matter what I use Double, String or Int there is no data coming back.
Here is a part of my code that is working.
var temperatureArray: Array<Double> = Array()
var dateArray: Array<String> = Array()
var iconArray: Array<String> = Array()
var dayNumber = 0
var readingNumber = 0
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
if let mainArray = jsonObj!.value(forKey: "list") as? NSArray {
for dict in mainArray {
if let mainDictionary = (dict as! NSDictionary).value(forKey: "main") as? NSDictionary {
if let temperature = mainDictionary.value(forKey: "temp_max") as? Double {
if readingNumber == 0 {
temperatureArray.append(temperature)
} else if temperature > temperatureArray[dayNumber] {
temperatureArray[dayNumber] = temperature
}
} else {
print("Error: unable to find temperature in dictionary")
}
if let date = (dict as! NSDictionary).value(forKey: "dt_txt") as? String {
if readingNumber == 0 {
dateArray.append(date)
}
}
} else {
print("Error: unable to find main in dictionary")
}
if let icon = (dict as! NSDictionary).value(forKey: "icon") as? String {
if readingNumber == 0 {
iconArray.append(icon)
}
}
readingNumber += 1
if readingNumber == 8 {
readingNumber = 0
dayNumber += 1
}
}
I get no build errors, but cannot draw data for the icon array.
#Vadian, thank you!! I took me a while, but we were actually trying to break though 2 Array Strings to get to the "icon" key!! this is how I did it.
if let mainArray = jsonObj!.value(forKey: "list") as? NSArray {
for dict in mainArray {
if let weatherArray = (dict as AnyObject).value(forKey: "weather") as? NSArray {
if let weatherDictionary = weatherArray[0] as? NSDictionary {
if let icon = weatherDictionary.value(forKey: "icon") as? String {

Swift 2 - User's Current Location is inside MKPolygon

I am trying to check if the user's current location is inside the MKPolygon. I have created the following function but it returns false for all my test cases. Is there something I might be doing wrong?
func isCorrectRegion(coordinates: Array<JSON>, userLocation: CLLocationCoordinate2D) -> Bool {
var newCoordinates: [CLLocationCoordinate2D] = []
var mapPoints: [MKMapPoint] = []
for(a):(JSON) in coordinates {
let lat = a.arrayValue[1].double
let long = a.arrayValue[0].double
let location = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
newCoordinates.append(location)
}
for b in newCoordinates {
let c: MKMapPoint = MKMapPointForCoordinate(b)
mapPoints.append(c)
}
let polygon: MKPolygon = MKPolygon(points: &mapPoints, count: mapPoints.count)
let polyRender: MKPolygonRenderer = MKPolygonRenderer(polygon: polygon)
polyRender.invalidatePath()
let target: MKMapPoint = MKMapPointForCoordinate(userLocation)
let cgTarget: CGPoint = CGPoint(x: target.x, y: target.y)
let isWithin = CGPathContainsPoint(polyRender.path, nil, cgTarget, false)
return isWithin
}
Finally figured it out after trying a few different things. Hope this helps others:
func isCorrectRegion(coordinates: Array<JSON>, userLocation: CLLocationCoordinate2D) -> Bool {
var newCoordinates: [CLLocationCoordinate2D] = []
var mapPoints: [MKMapPoint] = []
let mpr: CGMutablePathRef = CGPathCreateMutable()
for(a):(JSON) in coordinates {
let lat = a.arrayValue[1].double
let long = a.arrayValue[0].double
let location = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
newCoordinates.append(location)
}
for b in newCoordinates {
let c: MKMapPoint = MKMapPointForCoordinate(b)
mapPoints.append(c)
}
for var p = 0; p<mapPoints.count; p++ {
if p == 0 {
CGPathMoveToPoint(mpr, nil, CGFloat(mapPoints[p].x), CGFloat(mapPoints[p].y))
} else {
CGPathAddLineToPoint(mpr, nil, CGFloat(mapPoints[p].x), CGFloat(mapPoints[p].y))
}
}
let target: MKMapPoint = MKMapPointForCoordinate(userLocation)
let cgTarget: CGPoint = CGPoint(x: target.x, y: target.y)
let isWithin = CGPathContainsPoint(mpr, nil, cgTarget, false)
return isWithin
}

Swift 2 Ambiguous use of 'subscript' error

After upgrading to new version of xcode/swift I am getting lots of 'ambiguous use of subscript' errors.
The code in question is below, with the lines causing errors labelled with comments. Any ideas?
var exch: (AnyObject) = self.form.formValues().valueForKey(Static.exchange)!
if (exch.count != nil) {
if (exch.count==1) {
ex = exch[0] as! Int // error
} else if (exch.count==2) {
var i1 = exch[0] as! Int //error
var i2 = exch[1] as! Int //error
var total = i1 + i2
ex = total
} else if (exch.count==3) {
var i1 = exch[0] as! Int //error
var i2 = exch[1] as! Int //error
var i3 = exch[2] as! Int //error
var total = i1 + i2 + i3
ex = total
} else {
ex = 99
}
}
What is a type of exch? If it is an array of AnyObject change
var exch: (AnyObject)
to
var exch: [AnyObject]

Why is one label updating quicker then the other?

I am making my own Spotify controller to learn how to interact with AppleScript and Swift (using Objective-C as a bridge) to make a bigger project later on. The only issue is the current progress time seems to update slightly faster then the time left.
This is what my application looks like:
The time on the left seems to update slightly faster then the time on the right, this means it is not accurate and can be bit strange to look at. How would I be able to fix this so both the progress time and time left update at the same time?
Here is my code:
ViewController.swift
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var statusLabel: NSTextField!
#IBOutlet weak var songProgress: NSProgressIndicator!
#IBOutlet weak var lblCurrentProgress: NSTextField!
#IBOutlet weak var lblTrackLength: NSTextField!
//let debugger = Debug(appName:"Spotify Menu", debugable: )
var previousScript:String = ""
var toggleScript:String = ""
var nextScript:String = ""
var statusScript:String = ""
var artistScript:String = ""
var songNameScript:String = ""
var trackPosScript:String = ""
var trackLengthScript:String = ""
var trackIDscript:String = ""
var trackName:String = "unknown"
var artistName:String = "unknown"
var playerStatus:String = "unknown"
var trackID:String = "unknown"
var playerPosistion:Double = -1.0
var trackLength:Double = -1.0
var percentThrough:Double = -1.0
let timeFormatter = twoDiffrentTimes()
func main()
{
getStatus()
getSongName()
getArtist()
getTrackLength()
getPlayerPos()
getID()
percentThrough = (playerPosistion/trackLength)*100
if(playerStatus == "playing" && trackName != "unknown" && artistName != "unknown")
{
statusLabel.stringValue = "Spotify is currently playing the song \"\(trackName)\" by \"\(artistName)\""
} else if(playerStatus == "paused"){
statusLabel.stringValue = "Spotify is currently paused"
} else if(playerStatus == "stopped") {
statusLabel.stringValue = "Spotify is not playing any music"
} else {
statusLabel.stringValue = "There is currently an error"
}
//NSLog("The song is currently \(percentThrough.toDecimalPlace("2"))% the way in")
songProgress.doubleValue = percentThrough
timeFormatter.update(playerPosistion, timeTwo: trackLength-playerPosistion)
lblCurrentProgress.stringValue = timeFormatter.timeOneString
lblTrackLength.stringValue = timeFormatter.timeTwoString
}
override func viewDidLoad() {
super.viewDidLoad()
previousScript = readFile("previousTrack")
if(previousScript == "")
{
NSLog("Error finding previous track script")
exit(1)
}
toggleScript = readFile("playPause")
if(toggleScript == "")
{
NSLog("Error finding toggle script")
exit(1)
}
nextScript = readFile("nextTrack")
if(nextScript == "")
{
NSLog("Error going forwared a track")
exit(1)
}
statusScript = readFile("playerStatus")
if(statusScript == "")
{
NSLog("Error going back a track")
statusLabel.stringValue = "Spotify is in an unknown status"
exit(1)
}
artistScript = readFile("getArtist")
if(artistScript == "")
{
NSLog("Cannot get artist script")
exit(1)
}
songNameScript = readFile("getSongName")
if(songNameScript == "")
{
NSLog("Cannot get song name script")
exit(1)
}
trackPosScript = readFile("playerPosition")
if(trackPosScript == "")
{
NSLog("Error getting track posistion script")
exit(1)
}
trackLengthScript = readFile("durationOfSong")
if(trackLengthScript == "")
{
NSLog("Error getting track length script")
exit(1)
}
trackIDscript = readFile("trackID")
if(trackIDscript == "")
{
NSLog("Error getting")
}
main()
NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("main"), userInfo: nil, repeats: true)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func previous(sender: AnyObject)
{
runAppleScript(previousScript)
}
#IBAction func toggle(sender: AnyObject)
{
runAppleScript(toggleScript)
}
#IBAction func next(sender: AnyObject)
{
let nextFile = readFile("nextTrack")
if(nextFile == "")
{
NSLog("Error going forwared a track")
} else {
runAppleScript(nextFile)
}
}
func getPlayerPos()
{
playerPosistion = runAppleScript(trackPosScript).toDouble()
}
func getTrackLength()
{
trackLength = runAppleScript(trackLengthScript).toDouble()
}
func getSongName()
{
trackName = runAppleScript(songNameScript)
}
func getArtist()
{
artistName = runAppleScript(artistScript)
}
func getID()
{
trackID = runAppleScript(trackIDscript)
}
func getStatus()
{
let resultData = runAppleScript(statusScript)
if(resultData == "playing" || resultData == "paused" || resultData == "stopped")
{
playerStatus = resultData
} else {
playerStatus = "unknown"
}
}
}
classes.swift
import Foundation
class twoDiffrentTimes
{
var timeOne:Double = 0.0
var iMinuteOne:Int = 0
var iSecondsOne:Int = 0
var minuteOne:String = ""
var secondsOne:String = ""
var timeOneString:String = ""
var uSecondsOne:Double = 0.0
var temp:Int = 0
var timeTwo:Double = 0.0
var iMinuteTwo:Int = 0
var iSecondsTwo:Int = 0
var minuteTwo:String = ""
var secondsTwo:String = ""
var timeTwoString:String = ""
var uSecondsTwo:Double = 0.0
func update(timeOne:Double, timeTwo:Double)
{
//First Time
self.temp = Int(timeOne)
self.iMinuteOne = temp / 60
self.iSecondsOne = temp % 60
self.minuteOne = "\(iMinuteOne)"
if(self.iSecondsOne < 10)
{
self.secondsOne = "0\(self.iSecondsOne)"
} else {
self.secondsOne = "\(self.iSecondsOne)"
}
self.timeOneString = "\(self.iMinuteOne).\(self.secondsOne)"
//Second Time
self.temp = Int(timeTwo)
self.iMinuteTwo = temp / 60
self.iSecondsTwo = temp % 60
self.minuteTwo = "\(iMinuteTwo)"
if(self.iSecondsTwo < 10)
{
self.secondsTwo = "0\(self.iSecondsTwo)"
} else {
self.secondsTwo = "\(self.iSecondsTwo)"
}
self.timeTwoString = "\(self.iMinuteTwo).\(self.secondsTwo)"
}
}
extensions.swift
import Foundation
extension String {
func toDouble() -> Double {
if let unwrappedNum = Double(self) {
return unwrappedNum
} else {
// Handle a bad number
print("Error converting \"" + self + "\" to Double")
return 0.0
}
}
}
extension Double {
func toDecimalPlace(f: String) -> String {
return NSString(format: "%0.\(f)f", self) as String
}
func decimalValue() -> Int
{
if let decimalString = String(self).componentsSeparatedByString(".").last, decimal = Int(decimalString) {
return decimal // 535
} else {
return -1
}
}
}
functions.swift
import Foundation
func readFile(fileName: String) -> String{
if let filepath = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") {
do {
let contents = try NSString(contentsOfFile: filepath, usedEncoding: nil) as String
print(contents)
return contents
} catch {
NSLog("Content Could Not Be Loaded")
return ""
}
} else {
NSLog("File \(fileName).\("txt") could not be found")
return ""
}
}
func runAppleScript(script:String) -> String
{
let theResult:String
let errorInfo = AutoreleasingUnsafeMutablePointer<NSDictionary?>()
let startAtLoginScript: NSAppleScript = NSAppleScript(source: script)!
let theDiscriptor:NSAppleEventDescriptor = startAtLoginScript.executeAndReturnError(errorInfo)
if let _ = theDiscriptor.stringValue
{
theResult = theDiscriptor.stringValue!
} else {
theResult = ""
}
return theResult
}
errorClases.swift
import Foundation
enum MyAppleScriptError: ErrorType {
case ExecutingScriptFailed
case GettingStringValueFailed
}
Last but not least durationOfSong.txt (AppleScript)
tell application "Spotify"
set songLength to (duration of current track) / 1000 as string
return songLength
end tell
And playerPosition
tell application "Spotify"
set currentPosistion to player position as string
return currentPosistion
end tell
Edit:
Updated code
I recommend you learn how to call AppleScript handlers directly from Swift via the AppleScript-ObjC bridge. That will work vastly better than mucking about with code strings and NSAppleScript, which is slow and nasty and not a good way to do it. Tutorial here:
http://macscripter.net/viewtopic.php?id=43127
--
ETA:
"I have successful moved NSAppleScript to Swift2. Only thing is that still doesn't fix the issue. it is still out of timing."
Well, that's annoying. FWIW, I'd ditch that twoDiffrntTimes class as it doesn't do anything that can't be done in a single-line function, and change the end of main() to this:
func main() {
...
lblCurrentProgress.stringValue = formatTime(Int(playerPosistion))
lblTrackLength.stringValue = formatTime(Int(trackLength-playerPosistion))
}
func formatTime(secs: Int) -> String {
return NSString(format: "%i.%02i", secs / 60, secs % 60) as String
}

Replacing NSNulls inside NSDictionary

this question is similar to Replace occurrences of NSNull in nested NSDictionary
In swift I am getting an error (I believe because of NSNull's) I don't really care if the NSNull becomes an empty string or a nil. I am just wanting to get the code to work.
I have a large data structure coming in from JSON as an NSDictionary. Then I am saving that to a temporary file. Here is the code:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
let json = JSON(jsonResult)
if (json["errors"].array?.count > 0) {
println("could not load stuff")
} else {
println("retrieving the stuff")
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
//--- need to handle the NSNull junk here
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
Here's an example of what jsonResult looks like
things = (
{
"one" = one;
two = "<null>";
"three" = three;
"four" = "<null>";
"five" = five;
"six" = "six-6";
seven = 7;
eight = eight;
nine = "<null>";
ten = "<null>";
eleven = "<null>";
"twelve" = "<null>";
},
UPDATE:
Problem: I have a very large amount of JSON (roughly 600kb as text) Within that JSON data there are nulls. The problem I was having is that when you NSJSONSerialization as NSDictionary, it converts the nulls into NSNull objects (it looks funky if you print this out because they appear as a string, this is wrong.
Solution: You need to have a "pruned" or "sanitized" dictionary. What this means is to throw out the key and value entirely. To do this, I added a sanitized_dict function. Here is the function:
func sanitize_dict(obj: AnyObject) -> AnyObject {
if obj.isKindOfClass(NSDictionary) {
var saveableObject = obj as! NSMutableDictionary
for (key, value) in obj as! NSDictionary {
if (value.isKindOfClass(NSNull)) {
//println("Removing NSNull for: \(key)")
saveableObject.removeObjectForKey(key)
}
if (value.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(value as! NSArray)
saveableObject.setValue(tmpArray, forKey: key as! String)
}
if (value.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(value as! NSDictionary)
saveableObject.setValue(tmpDict, forKey: key as! String)
}
}
return saveableObject
//--- because arrays are handled differently,
//--- you basically need to do the same thing, but for an array
//--- if the object is an array
} else if obj.isKindOfClass(NSArray) {
var saveableObject = [AnyObject]()
for (index, ele) in enumerate(obj as! NSArray) {
if (ele.isKindOfClass(NSNull)) {
// simply don't add element to saveableobject and we're good
}
if (ele.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(ele as! NSArray)
saveableObject.append(tmpArray)
}
if (ele.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(ele as! NSDictionary)
saveableObject.append(tmpDict)
}
}
return saveableObject
}
// this shouldn't happen, but makes code work
var saveableObject = [AnyObject]()
return saveableObject
}
So your other code needs to call that function, it should look something like this:
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
//--- right now jsonResult is not actual json, and actually has the NSNulls
//--- get that result into the sanitized function above
let saveableDict: (AnyObject) = self.sanitize_dict(jsonResult)
let json = JSON(saveableDict)
if (json["errors"].array?.count > 0) {
println("!!!Failed to load.")
} else {
println("Load json successful. Attempting to save file...")
//--- set up basic structure for reading/writing temp file
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
Hope this helps somebody out there with a big JSON dataset and nulls. It is all about that sanitize function!

Resources