所以我处于学习swift的早期阶段,并且我试图创建一个简单的类来包装从给定的Web服务发送/检索数据的过程。我遇到的问题是,在发送请求或任何类型的响应后,没有任何内容正在打印到控制台。我真的很感激任何关于我做错的帮助或指导
import Foundation
class URLHelper : NSObject,NSURLConnectionDelegate,NSURLConnectionDataDelegate{
var data = NSMutableData()
func sendReq(){
let urlPath: String = "http://localhost/web-service/action.php?callback=showUserDetails&uid=1"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url,cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 4)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
println(error.description)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
var req = URLHelper()
req.sendReq()
<?php
//Get the action to run the coorect request
if(isset($_GET['callback'])){
$function = $_GET['callback'];
call_user_func($function);
//$function();
}else{
echo "Error: No valid callback supplied to request";
}
function showUserDetails(){
$conn = mysqli_connect("localhost", "root", "root", "service_db") or die("Error " . mysqli_error($conn));
$userid = $_GET['uid'];
$results = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM user WHERE id = $userid"));
mysqli_close($conn);
echo json_encode($results);
}
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
返回的json如下{"id":"1","username":"tom","email":"tom_smith@gmail.com"}
答案 0 :(得分:0)
对于发布,您无需提出请求,只需从网址获取内容:
var strResult:NSString
let strURL = "http://localhost/web-service/action.php?callback=showUserDetails&uid=1"
var dataURL = NSData(contentsOfURL: NSURL(string: strURL)!);
if let d = dataURL
{
strResult = NSString(data: d, encoding: NSUTF8StringEncoding)!
println(strResult)
}
在这里,我只需转到网址,获取内容并将其存储在数据对象中,然后将其转换为字符串并打印即可。您还可以将JSON字符串(strResult)解码为JSON对象。
希望有所帮助:)
答案 1 :(得分:0)
您可以使用具有completionHandler的此方法从Web服务中获取结果
func postAsync(backendMethodName:String ,body: [[String:String]], completionHandler: (resultnig:String) -> Void)
{
let session: NSURLSession = NSURLSession.sharedSession()
let urlPath: String = "\(sessionclass.connectionString)/\(backendMethodName)"
let request = NSMutableURLRequest(URL: NSURL(string:urlPath)!)
request.HTTPMethod = "POST"
request.timeoutInterval=10
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else
{
print("no data found: \(error)")
return
}
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
completionHandler(resultnig: strData as! String)
}
task.resume()
}
它采用后端方法Name(在Web服务中)和你的jsonData
你可以这样称呼它: self.postAsync("checkConnection", body: self.alldictionariesConn, completionHandler: { (resultnig) in
print(resulting) })//resulting = result from your web service