http post method passing multiple json parameters with alamofire in swift 2.0 - swift

strong text this is my code to pass two parameters(jsonData and device_Secret) to httpBody for that i should get following son in response
{"success":false,"msg":"Key not created plz try again."}
but i m getting this
responseString = Optional({"success":false,"msg":"Invalid Method"})
there is a problem in parameters format, what i am doing wrong?
my code is following /////////////
let JsonData = ["method":"device_token","params":["key":"1234jhg","device_id":"eb7e630a9637b0b83557e5a62121be8cb9210afb9aa5b878f819b775cb7d42a6"]]
let device_secret = ["params":["token":"-1","device_id":"9de47fb53c67eca4","key":"-1"]]
let params = ["data":JsonData, "device_secret":device_secret] as Dictionary<String, AnyObject>
let request = NSMutableURLRequest(URL: NSURL(string: "http://dev.jobsmarket.pk/api/v1")!)
print(request)
request.HTTPMethod = "POST"
let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(params)
print("NSdata of params is")
print(data)
NSJSONSerialization.isValidJSONObject(params)
print( NSJSONSerialization.isValidJSONObject(params))
// request.HTTPBody = params
request.HTTPBody = NSKeyedArchiver.archivedDataWithRootObject(params)
print("httpBody is ")
print(request.HTTPBody)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
/////////////////////////

Related

How can I translate the following code from Swift 2 to Swift 5?

I believe the following code below is written in Swift 2. How can the syntax be converted to the latest Swift (5)?
When using Xcode for conversion, it leaves me with errors like:
Extra argument 'usingEncoding' in call
and
Cannot call value of non-function type 'URLSession'
Original (Need Help Converting):
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.sample.com/sample.php")!)
request.HTTPMethod = "POST"
let postString = "a=\(customerLabel!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
This was my attempt but it has errors:
let request = NSMutableURLRequest(url: URL(string: "http://www.sample.com/sample.php")!)
request.httpMethod = "POST"
let postString = "a=\(customerLabel!)"
request.HTTPBody = postString.data(usingEncoding: NSUTF8StringEncoding)
let task = URLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
Don't use NSMutableURLRequest. Use URLRequest.
Don't use NSString, use String.
Look at the URLSession documentation and see that you need shared, not sharedInstance().
data(using .utf8).
Lots of other fixes.
Here's your fixed code with better handling of optionals in the completion handler:
var request = URLRequest(url: URL(string: "http://www.sample.com/sample.php")!)
request.httpMethod = "POST"
let postString = "a=\(customerLabel!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("error=\(error)")
return
}
print("response = \(response)")
if let data = data, let responseString = String(data: data, encoding: .utf8) {
print("responseString = \(responseString)")
}
}
task.resume()

How can I get variable to text from php to swift app

I use this code and work perfect. I use swift. PHP is work fine.
I also try some other examples at this
I have 2 problems
first my responseString values turns in Optional("Success"). Why?
second is How can assign it on my button?
func makePostCall() {
var request = URLRequest(url: URL(string: "MyURL/page.php")!)
request.httpMethod = "POST"
let postString = "id=login"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
self.lbl.text = responseString
}
task.resume()
//return responseString
}
You need to use DispatchQueue.main.async to work with UI from URLRequests. Also you need to use [weak self] to prevent reference cycle problem. At last, btn.setTitle(responseString, for: .normal) to set title for button state .normal. Here is correct answer!
func makePostCall() {
var request = URLRequest(url: URL(string: "MyURL/page.php")!)
request.httpMethod = "POST"
let postString = "id=login"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
guard let responseString = String(data: data, encoding: .utf8) else {
return
}
print("responseString = \(responseString)")
DispatchQueue.main.async {
self?.lbl.text = responseString
self?.btn.setTitle(responseString, for: .normal) // your button
}
}
task.resume()
//return responseString
}

Swift API call with URLSession gives 504 error

I have an API call with oauth which I tested with correct authorization token in postman.I am getting proper response in postman. But when I try same thing in Swift, I get 504 error.
I have checked every params and headers properly and everything looks same as postman. Not sure why samething is working in postman and gives 504 error in swift. what could be issue?
var params = [String : String]()
params["Id"] = Id;
var headers = [String : String]()
headers["api-key"] = "XXXXXX"
headers["Authorization"] = "Bearer XXX"
do{
var request = URLRequest(url: URL(string: getURL())!)
request.allHTTPHeaderFields = headers
request.httpBody = try JSONSerialization.data(withJSONObject: params , options: [])
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as! HTTPURLResponse
print(httpResponse)
}
task.resume()
}catch{
}
When using a GET request, there is no body to the request. Everything goes on the URL.
Also are you sure that in Postman you are using only those 2 headers?
See if something like this works for you:
var params: Parameters = Parameters()
params.updateValue(Id, forKey: "Id")
var components = URLComponents(string: getURL())!
components.queryItems = params.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
request.setValue("XXXXXX", forHTTPHeaderField: "api-key")
request.setValue("Bearer XXX", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()

Swift 3 How To Send A Multipart Post Request With Vapor

I'm using vapor to host images for my app.I have the following code to recieve the image and print it.
drop.post("saveArt") { request in
if let contentType = request.headers["Content-Type"], contentType.contains("image/png"), let bytes = request.body.bytes {
let image = NSImage(data: Data(bytes))
print(image)
return JSON(["Testawesome":"awesome123"])
}
return JSON(["test":"123"])
}
How can I send a multipart request using just swift?.Here is the current post request code i'm using.
let tiffData = imagetosend?.tiffRepresentation
let imageRep = NSBitmapImageRep(data: tiffData!)
let image_data = imageRep?.representation(using: .JPEG, properties: [:])
print("Hi")
let url = NSURL(string: "http://localhost:8080/getArt")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
//define the multipart request type
request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let mimetype = "image/png"
//define the data post parameter
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response , error == nil else {
print(error?.localizedDescription)
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString)
}
task.resume()
I solved it using this alamofire method.
Alamofire.request("YOUR URL", method: .post, parameters: parm, encoding: JSONEncoding.default).responseJSON(completionHandler: { json in
// If you want to return json.
print(json)
})

Connecting Swift with php server [duplicate]

This question already has answers here:
How can I get the Data from NSURLSession.sharedSession().dataTaskWithRequest
(2 answers)
Closed 6 years ago.
I'm trying to post from swift to php and then return json encoded data back to swift.
However, print(task.response) is nil. My link does what it is supposed to but my app still responds with nil. Any idea why?
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.flashkase.com/API/createAccount.php")!)
request.HTTPMethod = "POST"
let postString = "username=frogg222"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
print(task.response)
And my PHP file
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/database.php");
$arr = [];
$arr[] = 'Reporting for duty';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$arr[] = 'Post received';
$arr[] = $_POST['username'];
}
echo json_encode($arr);
?>
Update: How can I check for data after completion? If I uncomment sleep(3) it will display results...but that's obviously not ideal.
func postToServer(postURL: String, postString: String) {
let request = NSMutableURLRequest(URL: NSURL(string: postURL)!)
request.HTTPMethod = "POST"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
print("\(data), \(response), \(error)")
}
task.resume()
//sleep(3)
}
let sendURL: String = "https://www.flashkase.com/API/createAccount.php"
let sendData: String = "username=frogg222&email=fake123#gmail.com&password=fake1234"
postToServer(sendURL,postString: sendData)
dataTaskWithRequest is an asynchronous operation. Printing the response code immediately after the task starts will obviously print nil, as it hasn't had time to get a value. The completion handler already has a response object you can use, so inside your completion handler, call print(response) to see the properties and try to get a response code.