POST Connection from swift2 IOS to PHP - ios

I am little bit confused with code which i have used to post parameters to php webservice. Is this code creates post connection or just used get connection. because of maximum character limit (2048 max characters) of url i have to use post connection between iphone app and php file. Is this code works for long data like all latitudes and longitudes between two locations (later on will need to send it on server). I have searched a lot but i am still confused. Please help me guyz.
Code:
let request = NSMutableURLRequest(URL: NSURL(string: CommonUtils.webservice_path)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let postString = "type=updateUserDetail&Fname=" + fName + "&Lname=" + lName + "&mobile=" + mobileNo + "&phoneCode=" + countryCode + "&user_id=" + iUserId_str!
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if(data==nil){
}else{
}
})

Yes that code create a post method
the code i have used is below
SWIFT 2.0
let post:NSString = "Pram1=\(ratingUp)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://yoururltopost.com")! //change it to your url
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! //data is being encoded
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST" //setting method as post
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept") //set type of api
// request.setValue(apiKey, forHTTPHeaderField: "Authorization") // use if you are use Authorization
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func parseJson()
{
// do whatever you want to do
}else{
// show error
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Error"
alertView.message = "Please try after some time"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
dispatch_async(dispatch_get_main_queue(), parseJson)
}
}
task.resume()

There's 2 way for POST method, depends on the API, one is single URL and your request body is an dictionary (eg "type":"updateUserDetail",..), second is append your postString to the URL with empty body, what u doing is put the string that suppose to append to URL to the request body and that probably wont work

Related

How to pass two or many values in WKWebView's HTTP request body?

I want to pass two values in HTTP request body. I try to do it like this but it isn't working. can anyone help me?
guard let url = URL(string: "*****") else { return }
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let post: String = "cardId=\(viewModel.getCardId())&requestId=\(viewModel.getRequestId())"
if let postData: Data = post.data(using: String.Encoding.ascii, allowLossyConversion: true) {
request.httpBody = postData
webView.load(request as URLRequest)
}

How i can Load POST URLRequest with parameter in WKWebView?

Sorry For this my English is weak
I try many types of a solution but not working in Xcode 11.2.1 and swift 5
I try this
var urlRequest = URLRequest(url: URL(string: "https://xxxxxx/login")!)
urlRequest.httpMethod = "POST"
let params = [
"username": SessionManager.shared.username!,
"password": SessionManager.shared.password!,
"vhost": "standard"
]
let postString = self.getPostString(params: params)
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
...
//helper method to build url form request
func getPostString(params:[String:String]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
and this
Post Request with Parameter
And also try to add below lines in my code
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
But not Working
I fire the Request because not working the WKWebView screen is Open but not Load request.
If I not set navigationDelegate and open normal URL then it is working completely
If I set navigationDelegate then blank page come in all Request Like Normal URL fire or post parameter URL fire, All are coming to Blank Page in
I can't understand what is the Problem with WKWebView
Please help me.
Thanks in advance
The request body uses the same format as the query string:
parameter=value&also=another
Therefore the content type of your request is of type application/x-www-form-urlencoded :
let postString = self.getPostString(params: params)
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
Try this, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:
Set the webpage contents and base URL.
and the content is our converted string::-
var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
request.httpMethod = "POST"
let params = "Your Parameters"
request.httpBody = params.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
if data != nil {
if let returnString = String(data: data!, encoding: .utf8) {
self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
}
}
}
task.resume()
I think we not need to use URLSession.dataTask, simply create URLRequest and declare your method + with stating header fields like this:
private final func postRequestToURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
debugPrint("Error: Invailed URL!")
return
}
var parameters = Parameters()
parameters["name"] = "Example"
parameters["surname"] = "ExmpleExample"
parameters["timeZone"] = "MiddleEast/MENA"
parameters["test"] = "YES"
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.allowsCellularAccess = true
urlRequest.httpMethod = "POST"
let postString = parameters.getPostString()
urlRequest.httpBody = postString.data(using: .utf8)
if let wkNavigation = self.webView.load(urlRequest) {
debugPrint("Success: \(wkNavigation.description)")
} else {
debugPrint("Failure: Cannot load current request.")
}
}
Here we can convert our parameters to String by this extension:
public extension Dictionary where Key == String, Value == Any {
func getPostString() -> String {
var data = [String]()
for(key, value) in self {
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
}
I am using this code over my commercial app.
Additional info: I allowed request eligible to run over cellular by marking allowsCellularAccess = true this is optional

How to specify the type of Data being sent in URLRequest in Swift?

I am trying to understand how to specify the type of data sent in a URLRequest
using the URLRequest.addvalue() method in Swift.
For example I have learned that
URLRequest.addValue("applications/json", forHTTPHeaderField: "Content-Type")
specifies json data to be send.
If for instance I need to send in xml, how should I go about that?
Any resources will also be helpful!
Here we can't assign header field to URLRequest class directly. So make a variable of URLRequest first.
// create post request
let url = URL(string: "http://www.myserver.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// set header field
request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
// insert xml data to the request
let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
"<params class=\"API\">" +
"<param name=\"param1\">123213</param>" +
"<param name=\"param2\">1232131</param>" +
"</params>" +
"</msg>"
request.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
// api call
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
// process with data
print(data)
}
task.resume()

What's wrong i'm trying to post data using soap api but it's show me http 500 error

I'm trying to post in server but it doesn't connect to server .in this
Status Code: 500, Headers {"Cache-Control" = ( private ); "Content-Length" = ( 236
I've never used SOAP API. Can anyone help me? If you have any better solution then provide me.
import UIKit
class ViewController: UIViewController {
var is_SoapMessage = String(format: "<?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"
+ "<QR_GetDeviceCtration
xmlns='http://www.bdmitech.com/m2b'>\n"
+ "<TerminalName>%#</TerminalName>\n"
+ "<TerminalSerial>%#</TerminalSerial>\n"
+ "<ChannelType>%#</ChannelType>\n"
+ "<SecurityKey>%#</SecurityKey>\n"
+ "</QR_GetDeviceCheckAndRegistration>\n"
+ "</soap:Body></soap:Envelope>\n"
,"wegg","gewg","gerg","gerw","khds")
override func viewDidLoad() {
super.viewDidLoad()
self.soapcall()
}
func soapcall(){
let is_URL: String = "http://27.147.34.sdfre/eckAndRegistration"
let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
//let session = URLSession.shared
//let err: NSError?
let msgLength = String(describing: is_SoapMessage.characters.count)
lobj_Request.httpMethod = "POST"
// lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
lobj_Request.addValue("27.43.3553.32", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
lobj_Request.addValue("http://27.32423.23423.245:98/dRegistration", forHTTPHeaderField: "SOAPAction")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: lobj_Request as URLRequest ) { (data, response, error) in
print(response)
}
task.resume()
}
}

How to upload and associate an Image with a User in Parse.com (REST API), using Swift 2.0

I am trying to associate an image or a file with an object in Parse.com using the REST API. The Parse.com REST API Doc is quite vague, it talks about first how to upload which is fine, and then how to associate. The only issue is that it doesn't show how to associate with a User table, only an Object table, so when I tried to associate with a user, it asked for a username and password, and the response is as if it tries to create a new user. When I tried to associate with a regular table Company, it create a new entry. Any help would welcome, this is the code I have so far.
This is the code to upload a file to Parse.com with REST
let baseURL = NSURL(string: self.baseURL)
let url = NSURL(string: "/1/files/pic.jpg", relativeToURL: baseURL)
let request = NSMutableURLRequest()
request.HTTPMethod = "\(HTTPMethod.POST)"
request.addValue(appID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
let image = UIImage(named: "empAvatar")
let imageData = UIImageJPEGRepresentation(image!, 0.9)
let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let param = ["userProfile":base64String]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
} catch {
print("ERROR: HTTP Body JSON")
}
request.URL = url
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
data, response, error in
do {
let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
print("DATA: \(imageDic)")
} catch {
}
}
task.resume()
This is the code to associate a file with a user/object
let baseURL = NSURL(string: self.baseURL)
let url = NSURL(string: "/1/users/", relativeToURL: baseURL)
let request = NSMutableURLRequest()
request.HTTPMethod = "\(HTTPMethod.POST)"
request.addValue(appID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let param = ["name":"John", "picture":["name":"tfss-127e50c4-be6e-4228-b1a3-3f253358ac-pic.jpg","__type":"File"]]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
} catch {
print("ERROR: HTTP Body JSON")
}
request.URL = url
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
data, response, error in
do {
let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
print("DATA: \(imageDic)")
} catch {
}
}
task.resume()
With the URL, I also tried:
let url = NSURL(string: "/1/class/Company/", relativeToURL: baseURL)
And it just created a new entry.
Thanks you!
POST request will create new entry try using PUT method instead.

Resources