使用Swift发布到Web服务时,我很难检索数据。
我得到的只是我要返回的字符数,而不是实际字符。我认为它们一定在那里,我只是不知道如何检索它们。
这是我的Swift 3代码:
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)")
}
运行此代码时,得到以下输出:
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.
请特别注意上面的以下行:
data: Optional(45 bytes)
在服务器上运行的方法是一条简单的PHP行:
echo 'just a test string to return to the swift app';
这是45个字符
因此,按照我的看法,“数据”变量应该以某种方式包含回显的内容;还应该怎么知道字符数?
我只是不知道如何将它们取出来,并且我已经尝试了所有可以想到的方法(将方法调用放入变量中,将数据值分配给其他内容,将其转换为字符串,寻找toString方法,在这里Google搜索并搜索了类似的问题,甚至尝试了与Web完全不同的代码段,从而产生了相同的问题)。
我在应用程序的其他地方有代码,该代码通过简单的GET请求从服务器返回字符串,但是,这需要是POST-我只是还没有发布任何东西,因为它似乎无法正常工作。
我真的希望有人能告诉我发生了什么事。
最佳答案
您应该能够使用NSString
轻松地将该数据投射到NSString(data: data, encoding: NSUTF8StringEncoding)
。
要解开结果字符串(因为这是一个失败的初始化程序),请执行以下操作:
if let unwrappedDataString = dataString {
// Do things with the unwrapped string.
}
编辑:
要为您完美地编写此代码,请使用以下代码。如果您强行解包数据,则您的评论意味着如果由于某种原因不存在数据,则您的应用将崩溃。
if let unwrappedData = data {
if let dataString = NSString(data: unwrappedData, encoding: String.encoding.utf8.rawValue) {
// Do stuff
}
}