How to fetch data from SOAP WebService in Swift - swift

I need to get data from SOAP WebService in Swift https://codedump.io/share/JDHdwpOOmqne/1/swift-2-soap-web-service-call
I tried the procedures in the referred link but it was not working,Can any one help wit a working code.

You can use SWXML library for get data from soap web service this is easy to use and simple see the code below.
Alamofire.request(.GET, is_URL)
.responseJSON { response in
let xmls = SWXMLHash.parse(response.data!)
func enumerate(indexer: XMLIndexer, level: Int) {
for child in indexer.children {
let name:String? = child.element!.name
print("\(level) \(name)")
// Take Link from XML data here
if name! == "link" {
let text = child.element!.text
if text?.isEmpty == false{
print(text)
// Finish here Process
completion(result: text!)
}
}
enumerate(child, level: level + 1)
}
}
enumerate(xmls, level: 0)
}
}
And i having demo link also for this related code for Soap parsing Demo

Related

How to get data from call cloud functions using swift app?

Now I'm developing cloud functions.
Please teach me how to get data from call cloud functions using swift app.
I use TypeScript in cloud functions as backend service.
import * as functions from "firebase-functions"
import * as admin from "firebase-admin"
admin.initializeApp(functions.config().firebase)
export const helloWorld = functions
.https.onCall((data: any, context: any) => {
functions.logger.info("Hello logs!", { structuredData: true })
return { result: "Hello World" }
})
And in frontend I use swift.
func callCloudfunction(){
functions.httpsCallable("helloWorld").call(["name": "taro"]) { (result, error) in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
print(message)
}
}
if let data = (result?.data as? [String: Any]), let text = data["result"] as? String {
print("SUCCESS: \(text)")
}
}
}
In Swift I think functions.httpsCallable("helloWorld").call(["name": "taro"]) method is like http post request. So in TypeScript I can get the name's data using data argument.
But I don't know how to get result data from TypeScript. In TypeScript I created json { result: "Hello World" }.
How do I fix the process in swift? I think this code below is not good.
if let data = (result?.data as? [String: Any]), let text = data["result"] as? String {
print("SUCCESS: \(text)")
}
And please tell me how to handle error process.
Some class and property in error handling are already deprecated .FunctionsErrorDomain and FunctionsErrorDetailsKey.
Please teach me how to handle getting data and handle error process.
Thank you.

How to return data as a view model from alomofire coming from .net background

I am new to swift ui and am learning how to make an api call using alomofire.
I am from a csharp so bare with me if this is wrong I have a class that calls my api
My Understanding is I need a completion handler the data that is returned async so Im not sure what I need to do to extract the json properly and have a view model the following is my code
class webapilib{
var apiURLBase = "https://secreturl.com/api/"
init() {
}
func getFriends(completionHandler: ) {
performRequest()
}
func performRequest () {
let request = apiURLBase
var url = request + "Friends/GetAllParentsFriends?parentId=1"
AF.request(url).responseData { response in
switch response.result {
case .success(let value):
return String(data: value)
case .failure(let error):
print(error)
}
}
Example data
{"parents":[{"id":1,"type":null,"firstName":"Murry","groupId":null,"children":null,"emmailAddress":null,"surname":"Goldberg","name":null,"isParent":null,"isDeleted":false,"isActive":true,"createdBy":null,"lastModifiedBy":null,"lastUpdatedDate":null,"createdDate":null}],"children":[{"id":24864,"type":null,"orginizationId":null,"personId":null,"coachId":null,"teamId":null,"playerLevel":"A","fullName":"Audrey Lind","firstName":"Audrey","surname":"Lind","year":2008,"weight":null,"gender":null,"photo":null,"orgId":null,"ageGroup":null,"age":null,"emailAddress":"tandklind#msn.com","conditioningWorkouts":null,"conditioningWorkout":null,"bookings":null,"bikeWorkOuts":null,"isDeleted":false,"notes":null,"defaultTB":150.00,"defaultOP":15.00,"defaultPU":0.00,"defaultPB":null,"defaultBP":15.00,"defaultTBReps":5.00,"defaultOPReps":0.00,"defaultPUReps":10.00,"defaultPBReps":null,"defaultBPReps":0.00,"defaultAdvancedPuReps":0.00,"defaultAdvancedPu":0.00,"defaultPuSeconds":null,"defaultBroadJumpFeet":null,"defaultBroadJumpInches":null,"defaultTwentyFiveYards":null,"defaultOneFityYards":null,"status":0,"isActive":true,"createdBy":"System Import","lastModifiedBy":"Brandon","lastUpdatedDate":"2022-03-29T15:00:28.944125","createdDate":"2021-12-17T01:07:01.1819126"},{"id":24866,"type":null,"orginizationId":null,"personId":null,"coachId":null,"teamId":null,"playerLevel":"A","fullName":"Ellarae Atkinson","firstName":"Ellarae","surname":"Atkinson","year":2009,"weight":null,"gender":null,"photo":null,"orgId":null,"ageGroup":null,"age":null,"emailAddress":"atkinson_06#comcast.net","conditioningWorkouts":null,"conditioningWorkout":null,"bookings":null,"bikeWorkOuts":null,"isDeleted":false,"notes":null,"defaultTB":55.00,"defaultOP":20.00,"defaultPU":0.00,"defaultPB":null,"defaultBP":15.00,"defaultTBReps":2399.00,"defaultOPReps":0.00,"defaultPUReps":0.00,"defaultPBReps":null,"defaultBPReps":0.00,"defaultAdvancedPuReps":0.00,"defaultAdvancedPu":0.00,"defaultPuSeconds":null,"defaultBroadJumpFeet":null,"defaultBroadJumpInches":null,"defaultTwentyFiveYards":null,"defaultOneFityYards":null,"status":0,"isActive":true,"createdBy":"System Import","lastModifiedBy":null,"lastUpdatedDate":"2022-02-09T07:09:32.994522","createdDate":"2021-12-17T01:07:09.6571143"}]}
This is how am calling my from my button I eventually want this data in a list of some kind with card views
func callApi()
{
let api = thehockeylabapi().self
let test: () = api.getFriends()
}
my button click handler
Button("getFriends", action: callApi)
Again sorry for any messy code this is my first full week of learning so thanks in advance

Making HTTP request using Swift on OpenWhisk?

How can I make HTTP requests to retrieve and return data during a serverless Swift function running on Apache OpenWhisk?
Serverless cloud platforms restrict access to the runtime environment. This means you can't install extra libraries to help with this, e.g https://github.com/Alamofire/Alamofire.
The Swift runtime on Apache OpenWhisk does provide the following libraries pre-installed:
CCurl (0.2.3)
Kitura-net (1.7.10)
SwiftyJSON (15.0.1)
IBM Watson SDK (0.16.0)
The Kitura-net library provides a higher-level API for making HTTP requests than Swift's networking primitives (URLSession).
Here's an example of using that library to return data from an external JSON API as the function response.
import KituraNet
import Foundation
import SwiftyJSON
func httpRequestOptions() -> [ClientRequest.Options] {
let request: [ClientRequest.Options] = [
.method("GET"),
.schema("https://"),
.hostname("api.coindesk.com"),
.path("/v1/bpi/currentprice.json")
]
return request
}
func currentBitcoinPricesJson() -> JSON? {
var json: JSON = nil
let req = HTTP.request(httpRequestOptions()) { resp in
if let resp = resp, resp.statusCode == HTTPStatusCode.OK {
do {
var data = Data()
try resp.readAllData(into: &data)
json = JSON(data: data)
} catch {
print("Error \(error)")
}
} else {
print("Status error code or nil reponse received from App ID server.")
}
}
req.end()
return json
}
func main(args: [String:Any]) -> [String:Any] {
guard let json = currentBitcoinPricesJson() else {
return ["error": "unable to retrieve JSON API response"]
}
guard let rate = json["bpi"]["USD"]["rate_float"].double else {
return [ "error": "Currency not listed in Bitcoin prices" ]
}
return ["bitcoin_to_dollars": rate]
}
HTTP requests can be still be manually made using Swift's low-level networking primitives.

Swift dealing with classes, UIButtons and tableView

This might sound like a very stupid question but I am fairly new to swift and cannot think how to go about this. As you can see in this Screenshot I have a search recipes textfield in RecipesViewController where the user enters a food item (which I use in the api call). After the user hits the button I make a call to an api and get data from that api and store that data in instance variable (searchRecipe array) in my RecipesViewController class. Now I am trying to show the data that I received from the api in a table view so I have another class called SearchRecipeTViewController. n this class I want to populate the table with the data I received from the api however when I try to access the searchRecipe array (which stores the elements received from the api) I get a blank value which I understand is due to the instance variable being initialized as "". But now how do I go about this so that I can get data from the api and display it on the table view when the user hits the button. Any suggestions would be appreciated.
Code to call and get data from api when button is clicked
#IBAction func SearchButton(sender: UIButton) {
if let recipe = RecipeSearchBar.text {
searchRecipe = recipe
}
//search recipe API call
endpoint = "http://api.yummly.com/v1/api/recipes? _app_id=apiID&_app_key=apiKey&q=\(searchRecipe)"
Alamofire.request(.GET, endpoint).responseJSON { response in
if response.result.isSuccess {
let data = response.result.value as! NSDictionary
if let matches = data["matches"] as? [[String: AnyObject]] {
for match in matches {
if let name = match["recipeName"] as? String {
self.recipeName.append(name);
}
}
}
}
else if response.result.isFailure {
print("Bad request")
}
}
}
Try using SwiftyJSON to manipulate the JSON the API returns. SwiftyJSON makes API calls that use JSON much easier. Here is the code I used that uses both Alamofire and SwiftyJSON.
//Use alamofire to connect to the web service and use GET on it
Alamofire.request(url).responseJSON { response in
if let error = response.result.error {
print("Error: \(error)")
return
}
//Value is the response the webservice gives, given as a Data Obkect
if let value = response.result.value {
//The information given from the webservice in JSON format
let users = JSON(value)
print("The user information is: \(users)")
//Get each username in the JSON output and print it
for username in users.arrayValue{
print(username["username"].stringValue)
}
}
}
Forgot to add a link to SwiftJSON: https://github.com/SwiftyJSON/SwiftyJSON

Is it possible to use Soap API using Almofire in Swift 2.2

I am using both Rest & Soap API in my iOS application .For Rest API I can easily use Alamofire for both POST & GET method .But in Case of SOAP ,I am not able to handle the XML response .
Parse SOAP API using Alamofire and SWXMLHash Libraries easy to use for parsing : -
Swift 2.2
//MARK:- Parsing API here
func parseMyApi(is_URL: String, completion: (result: String) -> Void) {
Alamofire.request(.GET, is_URL)
.responseJSON { response in
let xmls = SWXMLHash.parse(response.data!)
func enumerate(indexer: XMLIndexer, level: Int) {
for child in indexer.children {
let name:String? = child.element!.name
print("\(level) \(name)")
// Take Link from XML data here
if name! == "link" {
let text = child.element!.text
if text?.isEmpty == false{
print(text)
// Finish here Process
completion(result: text!)
}
}
enumerate(child, level: level + 1)
}
}
enumerate(xmls, level: 0)
}
}
}
And you can see this example also for Soap parsing.