How to parse and fetch data from a soap web service within an ios app

How to parse and fetch data from a soap web service within an ios app

Answered by Claude31 in 113539022

You need to send the web service request to the appropritae server ; if it is a php API, that will be something like getFromWebServer in your IOS App.

I edited it rapidly to make it generic, so it may have some typos.


Hope that will help you.



    func generateBoundaryString() -> String {
        return "Boundary--\(NSUUID().UUIDString)" /
    }

    func createBodyWithParameters(parameters: [String: String]?, boundary: String) -> NSData {
        let theBody = NSMutableData(); /
        if parameters != nil {
            for (key, value) in parameters! {
                theBody.appendString("--\(boundary)\r\n")
                theBody.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                theBody.appendString("\(value)\r\n")
            }
        }
        theBody.appendString("--\(boundary)\r\n")
        return theBody
    }

    func getFromWebServer(IDClient: String) { /
        var retrievedData: Int?  /

        func post(url: String, postCompleted : (succeeded: Bool) -> ())    {

            let myUrl = NSURL(string: url)
            let request = NSMutableURLRequest(URL:myUrl!);
            request.HTTPMethod = "POST"
            let param = ["uid" : "\(IDClient)"]          // Param are the php request params, that match exactly the php script
            let boundaryString = generateBoundaryString()
            let contentType : String? = "multipart/form-data; boundary=\(boundaryString)"   /
            request.setValue(contentType, forHTTPHeaderField: "Content-Type")

            request.HTTPBody = createBodyWithParameters(param, boundary: boundaryString)
            sendIndicator.startAnimating();
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in                    /
                if error != nil {                            /
                    postCompleted(succeeded: false)         /
                    return  /
                }
                var json : NSDictionary?   /
                do {
                    let aDictionary :NSDictionary? = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
        
                    if let actualDictionary = aDictionary {
                       json = actualDictionary
                    }
                    else {
                    }
                }
                catch {
                    print("Error") /
                }
                if let parseJSON = json {
                    /
                    if let userData = parseJSON["myData"] as? Int { /
                        retrievedData = userData
                       postCompleted(succeeded: true)               /
                    }
                } else {
                    _ = NSString(data: data!, encoding: NSUTF8StringEncoding) /
                    postCompleted(succeeded: false)                 /
                }
            }
            task.resume()
        }
                        /
        let urlToGetMyData = addressIPServer! + "/lireDataFromApp.php";  // You should have a php script in your web server : lireDataFromApp.php
        post(urlToGetMyData) { (succeeded: Bool) -> () in          /
            if(succeeded) {
                if let myFullData= retrievedData {
                         // Do what you need withj your data
                }
            }

          dispatch_async(dispatch_get_main_queue()) {
                () -> Void in self.sendIndicator.stopAnimating()
        }
    }



The php script will look like this :


<?php

$form_uid = (isset($_REQUEST['uid'])) ? trim($_REQUEST['uid']) : '';
/ Opening DB */
$dbFile = $_SERVER['DOCUMENT_ROOT'] . "/MydataBase.db";
class MyDB extends SQLite3
{
  function __construct()
  {
  global $dbFile;
  $this->open($dbFile, SQLITE3_OPEN_READWRITE); /
  }
}
$db = new MyDB();
if(!$db) {
  echo json_encode([
  "Message" => "Error, not accessible", '<br>'
  ]);
  } else { /
}
$sql = "SELECT * FROM myTABLE where UID = '$form_uid'"; /
$ret = $db->query($sql);
/
if ($row = $ret->fetchArray(SQLITE3_ASSOC)) {
  $data = $row['DATA'];     // If you fetch data brom databae
    $data = (int) $data; /
  echo json_encode([
  "Message" => "data found",
  "data" => $data
  ], JSON_NUMERIC_CHECK);
}
?>

Nobody is going to write your app for you. If you have specific questions about the various steps you would need to follow (creating or parsing XML, making networking calls, etc.) then post those, with some code that reproduces the issues you're having. But don't expect someone to write an entire client-server networking stack and hand it to you on a silver platter.


And please stick to one thread per topic. Posting the same question multiple times is against the forum guidelines.

Accepted Answer

You need to send the web service request to the appropritae server ; if it is a php API, that will be something like getFromWebServer in your IOS App.

I edited it rapidly to make it generic, so it may have some typos.


Hope that will help you.



    func generateBoundaryString() -> String {
        return "Boundary--\(NSUUID().UUIDString)" /
    }

    func createBodyWithParameters(parameters: [String: String]?, boundary: String) -> NSData {
        let theBody = NSMutableData(); /
        if parameters != nil {
            for (key, value) in parameters! {
                theBody.appendString("--\(boundary)\r\n")
                theBody.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                theBody.appendString("\(value)\r\n")
            }
        }
        theBody.appendString("--\(boundary)\r\n")
        return theBody
    }

    func getFromWebServer(IDClient: String) { /
        var retrievedData: Int?  /

        func post(url: String, postCompleted : (succeeded: Bool) -> ())    {

            let myUrl = NSURL(string: url)
            let request = NSMutableURLRequest(URL:myUrl!);
            request.HTTPMethod = "POST"
            let param = ["uid" : "\(IDClient)"]          // Param are the php request params, that match exactly the php script
            let boundaryString = generateBoundaryString()
            let contentType : String? = "multipart/form-data; boundary=\(boundaryString)"   /
            request.setValue(contentType, forHTTPHeaderField: "Content-Type")

            request.HTTPBody = createBodyWithParameters(param, boundary: boundaryString)
            sendIndicator.startAnimating();
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in                    /
                if error != nil {                            /
                    postCompleted(succeeded: false)         /
                    return  /
                }
                var json : NSDictionary?   /
                do {
                    let aDictionary :NSDictionary? = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
        
                    if let actualDictionary = aDictionary {
                       json = actualDictionary
                    }
                    else {
                    }
                }
                catch {
                    print("Error") /
                }
                if let parseJSON = json {
                    /
                    if let userData = parseJSON["myData"] as? Int { /
                        retrievedData = userData
                       postCompleted(succeeded: true)               /
                    }
                } else {
                    _ = NSString(data: data!, encoding: NSUTF8StringEncoding) /
                    postCompleted(succeeded: false)                 /
                }
            }
            task.resume()
        }
                        /
        let urlToGetMyData = addressIPServer! + "/lireDataFromApp.php";  // You should have a php script in your web server : lireDataFromApp.php
        post(urlToGetMyData) { (succeeded: Bool) -> () in          /
            if(succeeded) {
                if let myFullData= retrievedData {
                         // Do what you need withj your data
                }
            }

          dispatch_async(dispatch_get_main_queue()) {
                () -> Void in self.sendIndicator.stopAnimating()
        }
    }



The php script will look like this :


<?php

$form_uid = (isset($_REQUEST['uid'])) ? trim($_REQUEST['uid']) : '';
/ Opening DB */
$dbFile = $_SERVER['DOCUMENT_ROOT'] . "/MydataBase.db";
class MyDB extends SQLite3
{
  function __construct()
  {
  global $dbFile;
  $this->open($dbFile, SQLITE3_OPEN_READWRITE); /
  }
}
$db = new MyDB();
if(!$db) {
  echo json_encode([
  "Message" => "Error, not accessible", '<br>'
  ]);
  } else { /
}
$sql = "SELECT * FROM myTABLE where UID = '$form_uid'"; /
$ret = $db->query($sql);
/
if ($row = $ret->fetchArray(SQLITE3_ASSOC)) {
  $data = $row['DATA'];     // If you fetch data brom databae
    $data = (int) $data; /
  echo json_encode([
  "Message" => "data found",
  "data" => $data
  ], JSON_NUMERIC_CHECK);
}
?>

Thank you...

Did it solve your problem ? If so, say it (correct answer)

How to parse and fetch data from a soap web service within an ios app
 
 
Q