I have 3 layers of data I'm getting from an xml that I need to store
1: Start time and end time
2: IP and mac address of a host
3: Port number and service of each host IP
The approach I used to solve this was to create 3 classes and let each have variables for the data like so:
class Ports {
var scanPortNumber: [String] = [""]
var scanProtocol: [String] = [""]
}
class Hosts {
var hostPorts = [Ports]()
var scanHostIP: [String] = [""]
var scanHostMacAddr: [String] = [""]
}
class Scan {
var scanHosts = [Hosts]()
var scanStartTime: [String] = [""]
var scanEndTime: [String] = [""]
}
then I declared a global object where i'm parsing the xml like this:
var scanDetails = Scan()
so I could store the IP's I get from the xml like this:
scanDetails.scanHosts[i].scanHostIP[i] = "the IP I get from parsing the xml"
here is how I'm trying to store the data:
var scanDetails = Scan()
class XMLRead: NSObject, XMLParserDelegate {
var hostIP = ""
var hostMacAddr = ""
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
var i = 0
if !elementName.isEmpty {
switch elementName {
case "address":
print("i in address = \(i)")
let addrType = attributeDict["addrtype"]
if addrType == "ipv4" {
let hostIPtmp = attributeDict["addr"]
if hostIPtmp != hostIP || hostIP == "" {
hostIP = hostIPtmp!
scanDetails.scanHosts[i].scanHostIP[i] = hostIP
}
}
else if addrType == "mac" {
let hostMacAddrtmp = attributeDict["addr"]
if hostMacAddrtmp != hostMacAddr || hostMacAddr == "" {
hostMacAddr = hostMacAddrtmp!
scanDetails.scanHosts[i].scanHostMacAddr[i] = hostMacAddr
}
}
print("hostIP = \(scanDetails.scanHosts[i].scanHostIP[i])")
print("hostMacAddr = \(scanDetails.scanHosts[i].scanHostMacAddr[i])")
default: break
}
i += 1
print("i = \(i)")
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("failure error: \(parseError)")
}
}
but this method doesn't seem to be working since it gives me the **Index out of range error** when I do this. So i tried using the append() method but it said I had to append a Hosts type and didn't allow me to append the value I get from the xml since it was a string.
I'm pretty new to swift so if someone can please tell me what am I doing wrong and how do I can fix it i'd be grateful.