1

I am parsing the XML data as the following and it is working in objective-C (I can show the objective-C code if needed.

//Update

//NSData
    response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://kalkatawi.com/jsonTest.php"]];

if(response!=nil) {

NSError *parseError = nil;

jsonArray1 = [[NSMutableArray alloc] init];

for(int i=0;i<[jsonArray count];i++)
{
    NSString  * city = [[jsonArray objectAtIndex:i] objectForKey:@"city"];

    [jsonArray1 addObject:city];

    NSLog(@"%@", jsonArray1);
}

My web result:

<city>1</city><city>2</city><city>3</city>

I have read this topic about How to parse a JSON file in swift? but I am getting an issue that "fatal error: unexpectedly found nil while unwrapping an Optional value" in the jsonData line. So please where would be my issue?

My code:

    let urlPath = "http://example.net/example/example.php"

    //Crash happens here
    let jsonData: NSData = NSData.dataWithContentsOfFile(urlPath, options: .DataReadingMappedIfSafe, error: nil)

    let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

    for parseData in jsonDict {

        println(parseData)
    }
Community
  • 1
  • 1
CAN
  • 1,677
  • 4
  • 19
  • 28
  • 3
    json? this looks like xml to me .. – meda Aug 18 '14 at 13:41
  • Thanks for the notice Sorry I have edited my question @meda – CAN Aug 18 '14 at 13:42
  • You can't parse XML with `NSJSONSerialization`. – Jesper Aug 18 '14 at 13:43
  • I thought I can while I am calling it in the objective-C as `[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://example.com/est.php"]];` @Jesper – CAN Aug 18 '14 at 13:44
  • 1
    No, you can't. Please show the working objective-C code and an actual example of the data you're getting back, something is off here. – jrturton Aug 18 '14 at 14:23
  • @jrturton I provided my code please check – CAN Aug 18 '14 at 14:27
  • Anyway guys I made a mistake and I am changing my code XML to JSON. Thanks for all you response and I am sorry again for that mistake. – CAN Aug 18 '14 at 14:29

1 Answers1

0

Edit: It looks like Apple has not implemented NSXMLDocument in Swift yet. Here is a library that might help you with parsing XML in Swift: https://github.com/ndavidsson/NDHpple

If it were implemented, this is how you would do it:

let urlPath:NSURL = NSURL(scheme:"http", host:"example.net", path:"example/example.php")
var error: NSErrorPointer? = nil
var xml:NSXMLDocument = NSXMLDocument(contentsOfUrl: urlPath, error: error!)

At that point, xml will represent an NSXMLDocument. https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSXMLDocument_Class/

tom.alexander
  • 219
  • 1
  • 6