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

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()

Related

Execute a PHP call from Swift passing one parameter - does not work yet

Trying to execute a call from Swift passing one parameter to PHP and getting the result
It does not execute the PHP call... not sure why?
func getInfo(_ dataValue:String){
print("in UserModel.getInfo")
let url: URL = URL(string: urlInfoPath)!
let rq = NSMutableURLRequest(url: url)
rq.httpMethod = "POST"
let postString = "a=\(dataValue)"
rq.httpBody = postString.data(using: String.Encoding.utf8)
print("PHP postString:", postString)
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) {
data, response, error in
print("UserModel.getINFO FROM PHP");
if error != nil {
print("error=\(String(describing: error))")
return
}
let val = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.responseString = val! as String
print("responseString = ", self.responseString)
}
}

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 http request crash nil value

I am using the following code to retrieve a response from a php page. Its works fine except every once in a while it crashes with an error after recieveing a nil value on the following line:
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
is there a way I can catch this?
let myUrl = NSURL(string: "https://*****backend/newmessage.php")
let request = NSMutableURLRequest(url: myUrl! as URL)
request.httpMethod = "POST"
let postString = "userid=\(userid!)"
print(postString)
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
if error != nil {
print("Error: \(error)")
}
DispatchQueue.main.async() {
print(responseString!)
if (responseString! == "NEW"){
self.messageIcon.setImage(UIImage(named: "newmessage.png"), for: UIControlState.normal)
}else{
self.messageIcon.setImage(UIImage(named: "envelope.png"), for: UIControlState.normal)
}
}
}
}
task.resume()
Why not address a potential nil w/ an if-else statement? Alternatively, you could use a guard statement.
if responseString != nil { // do stuff } else { // do other stuff}

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

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()
/////////////////////////

Can't upload image to server swift

I'm trying to upload an image to the server. As for now, I get an error response which checks if name='image', and the error means that it's not. The line where I set it is this:
body.appendString("Content-Disposition: form-data; name='image'; filename='test.jpg'")
my full code of the POST request is this: I do get a 200 and the only problem is with the name parameter which I really can't figure out.
func imageUploadRequest()
{
let stringUrl = "http://88.162.41.55/app_backend/public/api/v1/image?_r=1836486547600309"
let URL = NSURL(string: stringUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST";
request.setValue("Bearer \(jwtToken)", forHTTPHeaderField: "Authorization")
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
if(imageData == nil) {
print("image data is nil")
return
}
let body:NSMutableData = NSMutableData()
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name='image'; filename='test.jpg'")
body.appendString("Content-Type: image/jpg")
body.appendData(imageData!)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
request.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(" response = \(responseString!)")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
print("json", json)
} catch {
print("bad things happened")
}
}
task.resume()
}
Any ideas? Thank you so much!!
Sample NSURLSession
func getMetaData(lePath:String, completion: (string: String?, error: ErrorType?) -> Void) {
// **** get_metadata ****
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.dropboxapi.com/2/files/get_metadata")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("Bearer ab-blah", forHTTPHeaderField: "Authorization")
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("path", forHTTPHeaderField: lePath)
let cursor:NSDictionary? = ["path":lePath]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
request.HTTPBody = jsonData
print("json ",jsonData)
} catch {
print("snafoo alert")
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let error = error {
completion(string: nil, error: error)
return
}
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
//print("Body: \(strData)\n\n")
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
completion(string: "", error: nil)
} catch {
completion(string: nil, error: error)
}
})
task.resume()
}