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()
})
}
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
}
I want to change marker image in my MKPointAnnotation() and I have successfully changed my image but problem is that I have 2 marker points and I want to place ignitionon.png on point one and ignitionof.png on point two and my logic place ignitionon.png on both the points.
Code
if(self.doubelLocation) {
var pointOff = CLLocationCoordinate2D()
var pointOn = CLLocationCoordinate2D()
if(self.dateTime.count > 0) {
for(var i : Int = 0 ; i < self.dateTime.count ; i++) {
// print("Real status = \(self.dateTime[i])")
var fixTime = self.dateTime[i]
if(fixTime == self.dateTimeTwo) {
pointOff = CLLocationCoordinate2DMake(self.latt[i], self.lngg[i]);
print("pointOff = \(pointOff)")
//points.append(pointOf)
}
if(fixTime == self.dateTimeOne){
pointOn = CLLocationCoordinate2DMake(self.latt[i], self.lngg[i]);
print("pointOn = \(pointOn)")
//points.append(pointOf)
}
}
var points: [CLLocationCoordinate2D]
points = [pointOn, pointOff]
dispatch_async(dispatch_get_main_queue(), {
let geodesic = MKGeodesicPolyline(coordinates: &points[0], count: 2)
self.theMapView.addOverlay(geodesic)
let latDelta:CLLocationDegrees = 0.03
let lnggDelta:CLLocationDegrees = 0.03
UIView.animateWithDuration(1.5, animations: { () -> Void in
let span = MKCoordinateSpanMake(latDelta, lnggDelta)
let region1 = MKCoordinateRegion(center: points[0], span: span)
self.theMapView.setRegion(region1, animated: true)
self.ActivityIndicator.stopAnimating()
for(var i : Int = 0 ;i < points.count; i++){
var st = self.reportText[i]
// let theMarker = MKPointAnnotation()
//how to change marker color
//https://stackoverflow.com/questions/33532883/add-different-pin-color-with-mapkit-in-swift-2-1
let theMarker = MKPointAnnotation()
theMarker.coordinate = points[i]
// if(st == "IGNITION ON"){
if(i == 0){
theMarker.title = "Status : IGNITION OFF"
theMarker.subtitle = "\(self.locationOff)"
// theMarker.subtitle = "Date = , Reg#: "
self.theMapView.addAnnotation(theMarker)
let anView1:MKAnnotationView = MKAnnotationView()
anView1.annotation = theMarker
anView1.image = UIImage(named:"ignitionof")
anView1.canShowCallout = true
anView1.enabled = true
}
if(i == 1){
// theMarker = UIColor.greenColor()
theMarker.title = "Status : IGNITION ON"
theMarker.subtitle = "\(self.locationOn)"
// theMarker.subtitle = "Date = , Reg#: "
self.theMapView.addAnnotation(theMarker)
//how to change image of marker
//https://stackoverflow.com/questions/24467408/swift-add-mkannotationview-to-mkmapview
let anView:MKAnnotationView = MKAnnotationView()
anView.annotation = theMarker
anView.image = UIImage(named:"ignitionon")
anView.canShowCallout = true
anView.enabled = true
}
// }
}
})
})
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
//if annotation is not an MKPointAnnotation (eg. MKUserLocation),
//return nil so map draws default view for it (eg. blue dot)...
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView!.image = UIImage(named:"ignitionon")
anView!.canShowCallout = true
}
var anView1 = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView1 == nil {
anView1 = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView1!.image = UIImage(named:"ignitionof")
anView1!.canShowCallout = true
}
else {
//we are re-using a view, update its annotation reference...
anView!.annotation = annotation
}
return anView
}
I am following this Link:
Swift - Add MKAnnotationView To MKMapView
It's not the best way to handle multiple marker with different metadata.
You can't use mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) two times or more because in viewForAnnotation it is for only 1 view for each Point you have added in the stack.
Create a sub-class of MKPointAnnotation:
class CustomPointAnnotation: MKPointAnnotation {
var tag: String!
}
Create a Dictionary with all images:
var imagesPath : ["tag_1": "image_1.png", "tag_2": "image_2.jpg"]
Now in the delegate func, check Simply
if !(annotation is CustomPointAnnotation) {
return nil
}
and Handle the only one View you have:
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
var customannotation = annotation as! CustomPointAnnotation
anView!.image = UIImage(named: imagesPath(customannotation.tag))
anView!.canShowCallout = true
}
An example to add a new Custom point is:
let aPoint = CustomPointAnnotation()
aPoint.coordinate = CLLocationCoordinate2DMake(40.730872, -73.003066)
aPoint.title = "Info1"
aPoint.subtitle = "Subtitle"
aPoint.tag = "tag_1"
mapView.addAnnotation(aPoint)
I've been looking all over and can't seem to find an equivalent of String.unpack (ruby) for Swift. For example, I am trying to write these two statements in Swift:
offset = digest.unpack('#19C').first & 0x2f
value = digest.unpack("#{offset}#L").first
If anyone knows how I could accomplish this it would be very helpful, thank you!
EDIT:
Code so far:
import Foundation
class PasswordViewController: UIViewController {
#IBOutlet weak var simpleLabel: UILabel!
var email:String!
var LRA:String!
var sysid:String = "SECRET"
override func viewDidLoad() {
super.viewDidLoad()
var x:Int = 1446569017
reset_code(x)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
func reset_secret()->String {
return sysid.hmac(.SHA512, key: "THISISAKEY")
}
func reset_input(t:Int)->String{
var time:String = String(t)
var input:[String] = [sysid, email, time]
var stringrep:String = "|".join(input)
return stringrep
}
func reset_hmac(t:Int)->String{
var firstTime:String = reset_secret().hmac(.SHA256, key: reset_input(t))
return reset_secret().hmac(.SHA256, key: firstTime)
}
func reset_code(t:Int){
var time:Int = t / 43200
var digest:String = reset_hmac(t)
simpleLabel.text = digest
}
}
enum CryptoAlgorithm {
case SHA256, SHA512
var HMACAlgorithm: CCHmacAlgorithm {
var result: Int = 0
switch self {
case .SHA256: result = kCCHmacAlgSHA256
case .SHA512: result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
var digestLength: Int {
var result: Int32 = 0
switch self {
case .SHA256: result = CC_SHA256_DIGEST_LENGTH
case .SHA512: result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
func hmac(algorithm: CryptoAlgorithm, key: String) -> String {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
let digest = stringFromResult(result, length: digestLen)
result.dealloc(digestLen)
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
var hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
Is it possible to get the MAC address using Swift?
The MAC address being the primary address for the Wi-Fi or Airport.
I'm trying to make a OS X application.
Apple's sample code from https://developer.apple.com/library/mac/samplecode/GetPrimaryMACAddress/Introduction/Intro.html to retrieve the Ethernet MAC address can
be translated to Swift. I have preserved only the most important
comments, more explanations can be found in the original code.
// Returns an iterator containing the primary (built-in) Ethernet interface. The caller is responsible for
// releasing the iterator after the caller is done with it.
func FindEthernetInterfaces() -> io_iterator_t? {
let matchingDictUM = IOServiceMatching("IOEthernetInterface");
// Note that another option here would be:
// matchingDict = IOBSDMatching("en0");
// but en0: isn't necessarily the primary interface, especially on systems with multiple Ethernet ports.
if matchingDictUM == nil {
return nil
}
let matchingDict = matchingDictUM.takeUnretainedValue() as NSMutableDictionary
matchingDict["IOPropertyMatch"] = [ "IOPrimaryInterface" : true]
var matchingServices : io_iterator_t = 0
if IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &matchingServices) != KERN_SUCCESS {
return nil
}
return matchingServices
}
// Given an iterator across a set of Ethernet interfaces, return the MAC address of the last one.
// If no interfaces are found the MAC address is set to an empty string.
// In this sample the iterator should contain just the primary interface.
func GetMACAddress(intfIterator : io_iterator_t) -> [UInt8]? {
var macAddress : [UInt8]?
var intfService = IOIteratorNext(intfIterator)
while intfService != 0 {
var controllerService : io_object_t = 0
if IORegistryEntryGetParentEntry(intfService, "IOService", &controllerService) == KERN_SUCCESS {
let dataUM = IORegistryEntryCreateCFProperty(controllerService, "IOMACAddress", kCFAllocatorDefault, 0)
if dataUM != nil {
let data = dataUM.takeRetainedValue() as! NSData
macAddress = [0, 0, 0, 0, 0, 0]
data.getBytes(&macAddress!, length: macAddress!.count)
}
IOObjectRelease(controllerService)
}
IOObjectRelease(intfService)
intfService = IOIteratorNext(intfIterator)
}
return macAddress
}
if let intfIterator = FindEthernetInterfaces() {
if let macAddress = GetMACAddress(intfIterator) {
let macAddressAsString = ":".join(macAddress.map( { String(format:"%02x", $0) } ))
println(macAddressAsString)
}
IOObjectRelease(intfIterator)
}
The only "tricky" part is how to work with Unmanaged objects, those
have the suffix UM in my code.
Instead of returning an error code, the functions return an optional
value which is nil if the function failed.
Update for Swift 3:
func FindEthernetInterfaces() -> io_iterator_t? {
let matchingDict = IOServiceMatching("IOEthernetInterface") as NSMutableDictionary
matchingDict["IOPropertyMatch"] = [ "IOPrimaryInterface" : true]
var matchingServices : io_iterator_t = 0
if IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &matchingServices) != KERN_SUCCESS {
return nil
}
return matchingServices
}
func GetMACAddress(_ intfIterator : io_iterator_t) -> [UInt8]? {
var macAddress : [UInt8]?
var intfService = IOIteratorNext(intfIterator)
while intfService != 0 {
var controllerService : io_object_t = 0
if IORegistryEntryGetParentEntry(intfService, "IOService", &controllerService) == KERN_SUCCESS {
let dataUM = IORegistryEntryCreateCFProperty(controllerService, "IOMACAddress" as CFString, kCFAllocatorDefault, 0)
if let data = dataUM?.takeRetainedValue() as? NSData {
macAddress = [0, 0, 0, 0, 0, 0]
data.getBytes(&macAddress!, length: macAddress!.count)
}
IOObjectRelease(controllerService)
}
IOObjectRelease(intfService)
intfService = IOIteratorNext(intfIterator)
}
return macAddress
}
if let intfIterator = FindEthernetInterfaces() {
if let macAddress = GetMACAddress(intfIterator) {
let macAddressAsString = macAddress.map( { String(format:"%02x", $0) } )
.joined(separator: ":")
print(macAddressAsString)
}
IOObjectRelease(intfIterator)
}
Update for Swift 4.2
func FindEthernetInterfaces() -> io_iterator_t? {
let matchingDictUM = IOServiceMatching("IOEthernetInterface");
// Note that another option here would be:
// matchingDict = IOBSDMatching("en0");
// but en0: isn't necessarily the primary interface, especially on systems with multiple Ethernet ports.
if matchingDictUM == nil {
return nil
}
let matchingDict = matchingDictUM! as NSMutableDictionary
matchingDict["IOPropertyMatch"] = [ "IOPrimaryInterface" : true]
var matchingServices : io_iterator_t = 0
if IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &matchingServices) != KERN_SUCCESS {
return nil
}
return matchingServices
}
// Given an iterator across a set of Ethernet interfaces, return the MAC address of the last one.
// If no interfaces are found the MAC address is set to an empty string.
// In this sample the iterator should contain just the primary interface.
func GetMACAddress(_ intfIterator : io_iterator_t) -> [UInt8]? {
var macAddress : [UInt8]?
var intfService = IOIteratorNext(intfIterator)
while intfService != 0 {
var controllerService : io_object_t = 0
if IORegistryEntryGetParentEntry(intfService, kIOServicePlane, &controllerService) == KERN_SUCCESS {
let dataUM = IORegistryEntryCreateCFProperty(controllerService, "IOMACAddress" as CFString, kCFAllocatorDefault, 0)
if dataUM != nil {
let data = (dataUM!.takeRetainedValue() as! CFData) as Data
macAddress = [0, 0, 0, 0, 0, 0]
data.copyBytes(to: &macAddress!, count: macAddress!.count)
}
IOObjectRelease(controllerService)
}
IOObjectRelease(intfService)
intfService = IOIteratorNext(intfIterator)
}
return macAddress
}
func getMacAddress() -> String? {
var macAddressAsString : String?
if let intfIterator = FindEthernetInterfaces() {
if let macAddress = GetMACAddress(intfIterator) {
macAddressAsString = macAddress.map( { String(format:"%02x", $0) } ).joined(separator: ":")
print(macAddressAsString!)
}
IOObjectRelease(intfIterator)
}
return macAddressAsString
}
Different approach via if_msghdr
func MACAddressForBSD(bsd : String) -> String?
{
let MAC_ADDRESS_LENGTH = 6
let separator = ":"
var length : size_t = 0
var buffer : [CChar]
let bsdIndex = Int32(if_nametoindex(bsd))
if bsdIndex == 0 {
print("Error: could not find index for bsd name \(bsd)")
return nil
}
let bsdData = Data(bsd.utf8)
var managementInfoBase = [CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, bsdIndex]
if sysctl(&managementInfoBase, 6, nil, &length, nil, 0) < 0 {
print("Error: could not determine length of info data structure");
return nil;
}
buffer = [CChar](unsafeUninitializedCapacity: length, initializingWith: {buffer, initializedCount in
for x in 0..<length { buffer[x] = 0 }
initializedCount = length
})
if sysctl(&managementInfoBase, 6, &buffer, &length, nil, 0) < 0 {
print("Error: could not read info data structure");
return nil;
}
let infoData = Data(bytes: buffer, count: length)
let indexAfterMsghdr = MemoryLayout<if_msghdr>.stride + 1
let rangeOfToken = infoData[indexAfterMsghdr...].range(of: bsdData)!
let lower = rangeOfToken.upperBound
let upper = lower + MAC_ADDRESS_LENGTH
let macAddressData = infoData[lower..<upper]
let addressBytes = macAddressData.map{ String(format:"%02x", $0) }
return addressBytes.joined(separator: separator)
}
MACAddressForBSD(bsd: "en0")
Update to Martin R's entry. There are a couple of lines that won't compile with Swift 2.1.
Change:
let matchingDict = matchingDictUM.takeUnretainedValue() as NSMutableDictionary
To:
let matchingDict = matchingDictUM as NSMutableDictionary
Change:
let macAddressAsString = ":".join(macAddress.map( { String(format:"%02x", $0) } ))
To:
let macAddressAsString = macAddress.map( { String(format:"%02x", $0) } ).joinWithSeparator(":")
You can also use 'SystemConfiguration' framework
import SystemConfiguration
func collectMACAddresses() -> [String] {
guard let interfaces = SCNetworkInterfaceCopyAll() as? [SCNetworkInterface] else {
return []
}
return interfaces
.map(SCNetworkInterfaceGetHardwareAddressString)
.compactMap { $0 as String? }
}
DISCLAIMER: this is not production-ready. It would probably be rejected by the App Store. It's also subject to errors if the output of ifconfig changes in the future. I've made this because I lacked the skills to translate the C code given in the links. It does not replace a full Swift solution. That being said, it works...
Get ifconfig's output and parse it to get the MAC address associated with an interface (en0 in this example):
let theTask = NSTask()
let taskOutput = NSPipe()
theTask.launchPath = "/sbin/ifconfig"
theTask.standardOutput = taskOutput
theTask.standardError = taskOutput
theTask.arguments = ["en0"]
theTask.launch()
theTask.waitUntilExit()
let taskData = taskOutput.fileHandleForReading.readDataToEndOfFile()
if let stringResult = NSString(data: taskData, encoding: NSUTF8StringEncoding) {
if stringResult != "ifconfig: interface en0 does not exist" {
let f = stringResult.rangeOfString("ether")
if f.location != NSNotFound {
let sub = stringResult.substringFromIndex(f.location + f.length)
let range = Range(start: advance(sub.startIndex, 1), end: advance(sub.startIndex, 18))
let result = sub.substringWithRange(range)
println(result)
}
}
}