1
votes

I'm trying to make an HTTP request to a link; the response is in JSON.

I can't get the response correctly. I'm new with Swift and I don't know what the problem is…

The URL I'm trying to reach is http://url/test.r&pcTest=pTest

I already done this but in Objective C:

NSString *serviceURL = [NSString stringWithFormat:@"http://url/test.r&pcTest=pTest"];

 NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
    NSLog(@"null");
}

NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;

if (![response isEqualToString:@"UNAUTHORIZED"]) {
    response = [response stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    data = [response dataUsingEncoding:NSASCIIStringEncoding];
    NSLog(@"%@",response);
} else {
    //return nil;
    NSLog(@"dsfg");
}

And I got a correct answer. In Swift my code is:

let parameters = ["pcTest": "pTest"]
let urlPath :String = "http://url/test.r"
Alamofire.request(.POST, urlPath, parameters: parameters)
         .response { request, response, data, error in
            println(request)
            println(response)
            println(error)
            println(data)
    }

The response is

{ URL: http://url/test.r }

Optional( { URL: http://url/test.r} { status code: 200, headers { Connection = "Keep-Alive"; "Content-Type" = "text/javascript; charset=iso-8859-1"; Date = "Fri, 11 Sep 2015 22:34:12 GMT"; "Keep-Alive" = "timeout=5, max=400"; Server = "Apache/1.3.41 (Unix) mod_ssl/2.8.31 OpenSSL/0.9.8c"; "Transfer-Encoding" = Identity; } })

nil

Optional(<7b227474 41706172 7461646f 223a5b7b 22416e6f 223a2232 30313422 2c224376 655f4170 6172745f 4576616c 7561223a 22303122 2c224465 73637269 7063696f 6e223a22 43616c69 64616420 656e2065 6c204465 73656d70 65f16f20 446f6365 6e746522 7d2c7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3032222c 22446573 63726970 63696f6e 223a2244 65646963 616369f3 6e206120 6c617320 41637469 76696461 64657320 64652044 6f63656e 63696122 7d2c7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3033222c 22446573 63726970 63696f6e 223a2250 65726d61 6e656e63 69612065 6e206c61 73204163 74697669 64616465 73206465 20446f63 656e6369 61227d5d 2c227474 53656363 696f6e22 3a5b7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3031222c 22437665 5f536563 635f4576 616c7561 223a2230 31222c22

The response should be:

{"Bank":[{"Year":"2014","Clv":"01","Desc":"1345"},{"Year":"2014","Clv ... etc, etc

1

1 Answers

2
votes

If you want JSON parsing, you need to call responseJSON, not response:

let parameters = ["pcTest": "pTest"]
Alamofire.request(.GET, "http://url/test.r", parameters: parameters)
         .responseJSON { _, _, result in
             print(result)
             debugPrint(result)
         }