如何使用URLSessionTask

时间:2018-01-16 08:08:09

标签: swift swift3

嗨,大家好,我的代码即将使用,我正在制作一个pos系统,并与商家交谈,并将谈话返回到针垫。

我遇到的问题是,当我第一次购买时,它100%工作,我得到了服务的回复  。但是当我再做一次购买时它就没有任何反应。

我想知道任务是否已完成。我不知道有什么帮助

我可以通过重新启动应用程序来进行另一次调用

 func pinPad(Total:Int,echoData:Int64,retrievalReferenceNumber:Int64, cardAcceptorTerminalId:Int64,cardAcceptorIdCode:Int64) -> String
{

    getdata()
    var status:String = ""

let Message =  "<?xml version='1.0' encoding='utf-8'?>"


    var is_URL: String = "http://\(ipcon):\(portcon)/merchant/service"
    var session = URLSession.shared
    var lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    var task: URLSessionTask? = nil
    var err: NSError?

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = Message.data(using: String.Encoding.utf8)
    lobj_Request.addValue("http://\(ipcon):\(portcon)", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    //  lobj_Request.addValue(String(count(Message)), forHTTPHeaderField: "Content-Length")
    //lobj_Request.addValue("223", forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://\(ipcon):\(portcon)/merchant/service", forHTTPHeaderField: "SOAPAction")
    print("helo: \(lobj_Request)")

    if nil != task{
        task!.cancel()
        task = nil
    }
    let sem = DispatchSemaphore(value: 0)

   task = session.dataTask(with: lobj_Request as URLRequest){ data, response, error in
        if error != nil{
            return

        }else{
            let strData = NSString(data: (data)!, encoding: String.Encoding.utf8.rawValue) as! String
            print("Body: \(strData)")


            let xml = SWXMLHash.config {
                config in
                config.shouldProcessLazily = true
                }.parse(strData)



            if(xml["S:Envelope"]["S:Body"]["responseCode"].element?.text != nil)
            {
                status  = xml["S:Envelope"]["S:Body"]["responseCode"].element!.text
            }
            else{
                status  = xml["S:Envelope"]["S:Body"]["ns2:responseCode"].element!.text
            }
            sem.signal()

        }
        }
    task?.resume()

    sem.wait()
        session.invalidateAndCancel()
        return status

}

0 个答案:

没有答案