Cedric Simon Cedric Simon - 8 months ago 43
Swift Question

XCode swift HTTPS: String(data: data!, encoding: NSUTF8StringEncoding ) return nil

I am retrieving a HTML content from an HTTPS page, but for "short" content I do get it correctly. For "long" content I get a nil answer.

I don't know if content length has something to do with it.

My page either return a report in HTML (a small table with a couple of rows) or an "error" message if report is not found.

When the error message is returned, it "works well" --> I got the HTML response, but when it founds the report, I got a nil answer.

The report is working fine in HTML browser. I checked the apache logs and the answer content has the correct length, but Xcode got a nil answer.

I already checked dozen of "HTTPS nil request" questions found on Internet. HTTPS is not the problem. Code is working without need of having to put "Allow Arbitrary Loads" to true or adding "Exception Domains". Enabling these option do not solve the problem.

I have no idea what could cause this nil request while server is sending it.

let curUsuario=curTuc.nombre
let urlString = "https://xxxxxx.yyyyy.com/PatientLabDetails5?usuario=\(curUsuario)&pin=\(curnoPin)"
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in

print("response: \(response)")
print("Data: \(data?.length)")



response: Optional(<NSHTTPURLResponse: 0x7aea3f30> { URL: https://xxxx.yyyy.com/PatientLabDetails5?usuario=25808&pin=4884938 } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html;charset=ISO-8859-1";
Date = "Tue, 01 Nov 2016 14:07:29 GMT";
"Keep-Alive" = "timeout=15, max=100";
Server = Apache;
"Set-Cookie" = "JSESSIONID=2A38EC49C93927A34AA1C9ED16B5F997; Path=/; Secure; HttpOnly";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-XSS-Protection" = "1; mode=block";
} })

Data: 6015

But when I try to get the data, I got a nil result..

print(String(data: data!, encoding: NSUTF8StringEncoding ))

I tested it on 3 servers with apparently same apache settings, and exactly same web server code. On one it does work well, on the other 2 not. As usual, the one working is the one I don't need to use.

I checked the SSL certificate installation (just in case) on www.htbridge.com/ssl and got a A+ grade.


in my code usually make a fall back:

 var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
 if (strData == nil){
    //roll back to ASCII ...
        strData = NSString(data: data, encoding: NSASCIIStringEncoding)