向 php 网络服务发送 post 请求未在 swift 中返回任何值 2

Sending post request to php webservice is not returning any value in swift 2

我想调用或发送请求到我的 php 网络服务,它以 xml 格式生成响应,我需要解析该数据以获得声音 link 并发送它给玩家。

我写了下面的代码,但是当我调试它时没有返回任何响应。

有什么建议吗?

  var soapMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body<getSounds xmlns=\"http://test.com/soap/tv\"><Language></Language></getSounds></soap:Body></soap:Envelope>"


            let urlString: String = "http://test.com/tv/soapServices.php?wsdl"
            var url: NSURL = NSURL(string: urlString)!
            //var request: NSURLRequest = NSURLRequest(URL: url)
            var request = NSMutableURLRequest(URL: url)
            var msgLength = String(soapMsg.characters.count)

            request.HTTPMethod = "POST"
            request.HTTPBody = soapMsg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
            request.addValue("http://bee.myservice.com/userLogin", forHTTPHeaderField: "Action")



            var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
            connection.start()
            print(request)

            var response: NSURLResponse?

            //                        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?
            do{

                var data = try NSURLConnection.sendSynchronousRequest(request , returningResponse: &response)

                if let httpResponse = response as? NSHTTPURLResponse {
                    //                            print(<#T##items: Any...##Any#>)("error \(httpResponse.statusCode)")
                    print(response)
                }
            }
            catch{
                print("error")
            }

您的代码有误,

你必须使用委托方法

要接收响应,您已在 NSURLConnection 中编写 delegate 方法。

谢谢..

实现委托方法,

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
    // Recieved a new request, clear out the data object
    self.data = NSMutableData()
}

func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
    // Append the recieved chunk of data to our data object
    // If the connection is receiving some data
    self.data.appendData(conData)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    // Request complete, self.data should now hold the resulting info
    let responseString: NSString = NSString(data: self.responseData, encoding: NSUTF8StringEncoding);
    println(responseString)
}

这里 self.data 是 NSMutableData() 类型的变量,它存储 XML 响应。如果一切正常,responseString 应该打印 XML.

P.S别忘了这个 class YourClass : NSObject, NSURLConnectionDelegate

我找到了我的问题的解决方案,我想与其他想要使用它的人分享。

我使用 SOAPEngine 来处理 soap 请求这个框架在 Github 上可用,这就是我在 swift 2 中使用它的方式:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var SoundTitle:NSArray = [NSArray]()
    var soundfile:NSArray = [NSArray]()
    var soap = [SOAPEngine]()

    @IBOutlet var table: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let soap = SOAPEngine()
        soap.userAgent = "SOAPEngine"
        soap.actionNamespaceSlash = true
        soap.licenseKey = "eJJDzkPK9Xx+p5cOH7w0Q+AvPdgK1fzWWuUpMaYCq3r1mwf36Ocw6dn0+CLjRaOiSjfXaFQBWMi+TxCpxVF/FA=="
        //soap.responseHeader = true // use only for non standard MS-SOAP service

//        soap.setValue("1", forKey: "Language")//sending post variables to field one
        soap.setIntegerValue(1, forKey: "Language")//sending post variable to field two
        soap.requestURL("http://test.com/tv/soapServices.php",
            soapAction: "http://test.com/tv/soapServices.php/getSounds",
            completeWithDictionary: { (statusCode : Int, dict : [NSObject : AnyObject]!) -> Void in

                var book:Dictionary = dict as Dictionary
//                print(book)
//                print(book["Title"])
                let soundfile : NSArray = book["SoundPath"] as! NSArray
                let SoundTitle : NSArray = book["Title"] as! NSArray

                self.soundfile = soundfile
                self.SoundTitle = SoundTitle
                self.table.reloadData()


            }) { (error : NSError!) -> Void in

                NSLog("%@", error)
        }
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.soundfile.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell:UITableViewCell? = self.table.dequeueReusableCellWithIdentifier("cell") as UITableViewCell?
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        }

        let sound_file : String = self.soundfile[indexPath.row] as! String
        let sound_title : String = self.SoundTitle[indexPath.row] as! String


        cell!.textLabel?.text = sound_title
        cell!.textLabel!.textAlignment = .Right
        cell!.detailTextLabel?.text = sound_file


        return cell!
    }

}