Henry Henry - 22 days ago 5
Swift Question

Retrieving web string in Swift

I'm having a hard time retrieving data when I post to my web service using Swift.
All I get is the number of characters I am returning, not the actual characters. I figure they must be there, I just don't know how to retrieve them.

Here is my Swift 3 code:

let url: NSURL = NSURL(string: "http://www.nanorig.dk/api/login")!
let request:NSMutableURLRequest = NSMutableURLRequest(url:url as URL)

let bodyData = "data=something"
request.httpMethod = "POST"

request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
(response, data, error) in
print("response: \(response)")
print("data: \(data)")
print("error: \(error)")

When I run this code, I get the following output:

response: Optional(<NSHTTPURLResponse: 0x174225400> { URL: http://www.nanorig.dk/api/login } { status code: 200, headers {
"Accept-Ranges" = bytes;
Age = 0;
"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 85;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 06 Oct 2016 13:15:18 GMT";
Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
Pragma = "no-cache";
Server = Apache;
"Set-Cookie" = "PHPSESSID=6so30t6brvj6j5k03kihr1m1f5; path=/";
Vary = "Accept-Encoding";
Via = "1.1 varnish-v4";
"X-Powered-By" = "PHP/5.6.26";
"X-Varnish" = 159701416;
} })
data: Optional(45 bytes)
error: nil
2016-10-06 15:15:19.428231 NanOrig[2245:1192962] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2016-10-06 15:15:19.436932 NanOrig[2245:1192962] [MC] Reading from public effective user settings.

Notice, especially, the following line in the above:

data: Optional(45 bytes)

The method being run on the server is a simple PHP line:

echo 'just a test string to return to the swift app';

...this is 45 characters...

So, the way I see it, the "data" variable should somehow contain what is echoed; how else should it know the number of characters?
I just don't know how to get them out, and I have tried everything I can think of (putting the method call in a variable, assigning the data value to something else, casting it to a string, looked for a toString method, Googled and searched here for similar problems, even tried a completely different code snippet from the web, which yielded the same problem).

I have code elsewhere in my application that returns string from the server with simple GET requests, however, this needs to be a POST - I'm just not posting anything yet, since it doesn't seem to work.

I really hope someone can tell me what is going on.


You should be able to cast that Data to an NSString easily using NSString(data: data, encoding: NSUTF8StringEncoding).

To unwrap the resulting string (as this is a failable initialiser), do the following:

if let unwrappedDataString = dataString {
    // Do things with the unwrapped string.


To perfectly write this for you, use the following. Your comment had you force unwrapping data which means if for whatever reason data doesn't exist, your app will crash.

if let unwrappedData = data {
   if let dataString = NSString(data: unwrappedData, encoding: String.encoding.utf8.rawValue) {
          // Do stuff