How to pass two parameter into webservice
Rewrite your function
func single_news(userid: Int , newsid : Int) {}
I assume that newsid
is also an Int
value.
And write your postString
like this...
let postString = "userid=\(userid)&newsid=\(newsid)"
I hope this will help you.
swift send array to web service parameters
I solved the problem with below code:
var assigneesList = [[String:Any]]()
for a in task.YeniGorevAtamaList! {
assigneesList.append(
["assignedTo":(a.Id) ?? "0",
"assignedSurname":a.Surname ?? "",
"assignedType":a.assignedType ?? "PERSONEL",
"assignedName":a.Name ?? "",
"assignedEmail":a.Email as Any
]
);
}
let parameters = [
"taskType" :
[
"code" : "DIGER"
],
"assignees" : assigneesList ,
"taskUrls" :
[
]
] as [String : Any]
Swift GET request with parameters
When building a GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents
.
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
The only trick is that most web services need +
character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded
specification). But URLComponents
will not percent escape it. Apple contends that +
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded
requests and really should not be passed unescaped.
Apple acknowledges that we have to percent escaping the +
characters, but advises that we do it manually:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a +
character and you have a server that interprets them as spaces.
So, combining that with your sendRequest
routine, you end up with something like:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
200 ..< 300 ~= response.statusCode, // is statusCode 2XX
error == nil // was there no error
else {
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
And you'd call it like:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
Personally, I'd use JSONDecoder
nowadays and return a custom struct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.
See previous revision of this answer for Swift 2 and manual percent escaping renditions.
send parameter in soap web service from ios
This is easy create an NSString
NSString *soapMessage = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\">\n"
"<soap:Body>\n"
"<CreateNoteUsingXMl xmlns="http://www.myurl.com">\n"
" <Username>%@</Username>\n"
"<Mypass>%@</Mypass>\n"
"<NoteXML>%@</NoteXML>\n"
"</CreateNoteUsingXMl>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"
,username
, mypassword
, notexml
];
Now create NSURL
NSURL *url = [NSURL URLWithString:@"What Ever"];
Create NSMutableURLRequest
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]]
Do rest of things you want ...
Send parameters to a web service
some examples about GET Post SOAP
GET request
GET /index.html?userid=joe&password=guessme HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Post request
POST /login.jsp HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
userid=joe&password=guessme
Soap Request
POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
the HOST,User-Agent,Content-Length,Content-Type are items in the Request Header
Pass JSON result to second webservice to get final results using Alamofire Swift
You can the pass the response of first api directly by calling the second api inside the response block of the first api.
private func callFirstApi() {
Alamofire.request("http://GetConstantTableList", method: .get, encoding: encoding, headers: [ "Accept":"application/json", "Authorization":"Bearer \(token ?? "")"])
.responseJSON { response in
switch response.result {
case .success(let value):
if let parameters = value as? [String: Any] {
callSecondApi(with: parameters)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
private func callSecondApi(with parameters: [String: Any]) {
Alamofire.request("http://GetConstantTableData", method: .post, parameters: parameters, encoding: encoding, headers: [ "Accept":"application/json", "Authorization":"Bearer \(token ?? "")"])
.responseJSON { response in
print(response)
}
}
How to pass parameters in request while routing (Server Side Swift using Vapor)
The query string parameters will be in the query container and hence they can accessed like below.
router.get("users") { request -> Future<[User]> in
if let minimumAge = request.query[Int.self, at: "above_age"] {
return User.query(on: request).filter(\.age > minimumAge).all()
}
return User.query(on: request).all()
}
If the request has above_age as a query param, the router will return list of users above that age else it will return all users.
Related Topics
Googlemaps Basic iOS Demo App Crash - Unrecognized Selector Sent to Instance
I Get Conflicting Provisioning Settings Error When I Try to Archive to Submit an iOS App
Paging Uiscrollview in Increments Smaller Than Frame Size
Storyboards VS. the Old Xib Way
Navigating to a New Screen When Stream Value in Bloc Changes
Detecting Touches on Mkoverlay in iOS7 (Mkoverlayrenderer)
Convert Swiftui View to PDF on iOS
Xcode 5 Crashes -- Xcode Quit Unexpectedly
Ccavenue iOS Kit Integration Kit
Images Can't Contain Alpha Channels or Transparencies
Xcode 8/Swift 3: "Expression of Type Uiviewcontroller? Is Unused" Warning
Simulator Slow-Motion Animations Are Now On
iOS Designated Initializers:Using Ns_Designated_Initializer
How to Combine Two Dictionary Instances in Swift