可达性恢复时的SOAP调用

时间:2016-04-12 09:06:01

标签: ios swift soap reachability

我不想调用我的代码的一部分,我使用NSURLSession作为我的SOAP服务,我从我的SQLite数据库发送数据,当列statut的值等于0时发送数据,如果应用程序因为可访问性而无法发送数据,我将该值设置为0,但是如果用户通过执行以下操作终止应用程序:双击主页并将应用程序滑动到顶部以关闭它,我想和#39; t检查互联网是否是后端再次使用我的SOAP服务,但是如果用户关闭了我的应用怎么办?

SOAP:

class SOAP: NSObject, UITextFieldDelegate, NSXMLParserDelegate, NSURLSessionDataDelegate, NSURLSessionDelegate {

    var MutableData: NSMutableData = NSMutableData()
    var currentElementName: NSString = ""
    var soapServiceURL = ""
    var soapUsername = ""
    var soapPassword = ""
    var fonctionSoapOuverture = ""
    var fonctionSoapFermeture = ""

    var successSoap = 0

    init(url: String, username: String, password: String){
        self.soapServiceURL = url
        self.soapUsername = username
        self.soapPassword = password
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    func soapCall(fonction:String, messageSoap:String, completion: (result: Int)->()){
        if Reachability.isConnectedToNetwork() == true {
            let soapRequest = AEXMLDocument()
            let attributes = ["xmlns:SOAP-ENV" : "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:ns1" : "urn:contactFile", "xmlns:xsd" : "http://www.w3.org/2001/XMLSchema", "xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance", "xmlns:SOAP-ENC" : "http://schemas.xmlsoap.org/soap/encoding/", "SOAP-ENV:encodingStyle" : "http://schemas.xmlsoap.org/soap/encoding/"]
            let envelope = soapRequest.addChild(name: "SOAP-ENV:Envelope", attributes: attributes)
            let body = envelope.addChild(name: "SOAP-ENV:Body")
            let sendLead = body.addChild(name: "ns1:"+fonction)
            sendLead.addChild(name: "xml", attributes: ["xsi:type" : "xsd:string"], value: messageSoap)
            let soapMessage = soapRequest.xmlString
            let messageSoapMinify = minify(soapMessage)


            //        URL Soap
            let urlString = soapServiceURL
            let url = NSURL(string: urlString)
            let theRequest = NSMutableURLRequest(URL: url!)

            //        Taille SoapMessage
            let msgLength = String(messageSoapMinify.characters.count)

            //        Soap Login
            let username = soapUsername
            let password = soapPassword
            let loginString = NSString(format: "%@:%@", username, password)
            let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
            let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

            //        Requete Soap
            theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            theRequest.addValue("Keep-Alive", forHTTPHeaderField: "Connection")
            theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
            theRequest.addValue("urn:ResponseAction", forHTTPHeaderField: "SOAPAction")
            theRequest.HTTPMethod = "POST"
            theRequest.HTTPBody = messageSoapMinify.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            theRequest.addValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
            //        print("Request is \(theRequest.allHTTPHeaderFields!)")

            let session = NSURLSession.sharedSession()

            let task = session.dataTaskWithRequest(theRequest, completionHandler: {data, response, error -> Void in
                print("Response Login: \(response)")
                let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)!
                print("Body Login: \(strData)")
                if error != nil
                {
                    print("Error Login: " + error!.description)
                }
                let parser = NSXMLParser(data: data!)
                parser.delegate = self
                parser.parse()
                if(self.success == "1"){
                    self.successSoap = 1
                } else {
                    self.successSoap = 0
                }
                completion(result: self.successSoap)
            })


            task.resume()
        } else {

            completion(result: self.successSoap)
        }
    }


    var didStartElement = 0
    var didEndElement = 0
    var foundCharacters = 0


    func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && challenge.protectionSpace.host == Configuration.MyVariables.host {
            NSLog("yep authorised")
            let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!)
            challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
        } else {
            NSLog("nope")
            challenge.sender!.performDefaultHandlingForAuthenticationChallenge!(challenge)
        }

    }
    func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
        let xmlParser = NSXMLParser(data: MutableData)
        xmlParser.delegate = self
        xmlParser.shouldProcessNamespaces = false
        xmlParser.shouldReportNamespacePrefixes = false
        xmlParser.shouldResolveExternalEntities = false
    }
    func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
        print("error of \(error)")
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        MutableData.length = 0
    }


    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        MutableData.appendData(data)
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        print("error of \(error)")
    }

    var elementValue: String?
    var success = ""

    func parser(parser: NSXMLParser,didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        if elementName == "code" {
            elementValue = String()
        }
    }

    func parser(parser: NSXMLParser, foundCharacters string: String) {
        if elementValue != nil {
            elementValue! += string
        }
    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "code" {
            success = elementValue!
        }
    }

    func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
        print("parseErrorOccurred: \(parseError)")
    }

    func minify(message: String) -> String{
        let finalMessageSoap = message.stringByReplacingOccurrencesOfString("\n", withString: "").stringByReplacingOccurrencesOfString("\t", withString: "").stringByReplacingOccurrencesOfString("Optional(", withString: "").stringByReplacingOccurrencesOfString(")</xml>", withString: "</xml>")

        return finalMessageSoap

    }
}

我怎么称呼它:

let serviceSoap = SOAP(url: Configuration.MyVariables.url, username: Configuration.MyVariables.usernameSoap, password: Configuration.MyVariables.passwordSoap)
            let fonctionSoap = "SendLead"

            var statutEnvoie = 0

            serviceSoap.soapCall(fonctionSoap, messageSoap: messageSoapSendLead){ (result) in
                if result == 1 {
                    statutEnvoie = 1

                    /* Tracker écran */

                    let trackerv = GAI.sharedInstance().defaultTracker
                    trackerv.set(kGAIScreenName, value: "Demande Envoyé")

                    let builder = GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]
                    trackerv.send(builder)

                    /* Tracker transaction */

                    var rangeName = ""

                    if let startRange = messageSoapSendLead.rangeOfString("<Logement>"), endRange = messageSoapSendLead.rangeOfString("</Logement>") where startRange.endIndex <= endRange.startIndex {
                        rangeName = messageSoapSendLead[startRange.endIndex..<endRange.startIndex]
                    } else {
                        print("invalid input")
                    }

                } else {
                    statutEnvoie = 0
                }

如果statutEnvoie等于0

,我将数据保存在SQLite中

0 个答案:

没有答案