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

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

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 did swift make web requests

I`m a new swifter ,so can take me some help to use swift to make web requests,thanks. Why can't it be reviewed and submitted。
//创建请求体
let param = ["moblie":"18392387159"]
let data = try! JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions.prettyPrinted)
var string = "json="
let Str = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//拼接
string = string + Str!
let Url = URL.init(string: "http://huixin.smartdot.com:9901/GoComWebService/restful/GoComeRestful/getResetCode")
let request = NSMutableURLRequest.init(url: Url!)
request.timeoutInterval = 30
//请求方式,跟OC一样的
request.httpMethod = "POST"
request.httpBody = string.data(using: String.Encoding.utf8)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if (error != nil) {
return
}
else {
//此处是具体的解析,具体请移步下面
let json: Any = try! JSONSerialization.jsonObject(with: data!, options: [])
if let value = JSON(json)["status"].string {
print("状态是:\(value)")
}
print(json)
}
}
dataTask.resume()
i write like this , why it did not work !
I suggest you modify the following code
data is not recommended mandatory unpack ,I am here only to help you find the problem quickly to deal with this problem
do {
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print(dic)
} catch {
print(error)
}
Error returned here is
Error Domain = NSCocoaErrorDomain Code = 3840 "No value." UserInfo = {NSDebugDescription = No value.}
You may ask the parameters of the problem, check their own

How to use special characters \n in URL

I have POST request:
init (url: String,arg: String) {
self.responseString = nil
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
let postString = arg
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
self.responseString = nil
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { //
self.responseString = nil
} else {
self.responseString = String(data: data, encoding: .utf8)
}
}
task.resume()
}
When arg have a character \n, half arg text is lost. How fix this problem?
strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL.init(string: strUrl)
let requestURL = URLRequest(url: url!)
You need to add addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) method to allow URL Query.

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}

Is it possible to return result set from POST call

I have this code:
private func data_request(url : String)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let url:NSURL = NSURL(string: self.self.newUrl.createUrl(url))!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "data=Hello"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
task.resume()
}
}
I call it like this:
var result = data_request("localhost/test");
That is working fine, but is it possible to return the results from the request function? My plan is to put the result in the result variable.
You should use closures to get the data since the NSURLSession API is asynchronous, meaning that you don't know when the data will arrive. It may be instantly or in 10 seconds, you never know. You will return from the function immediately, but you'll get the value from the closure.
private func data_request(url : String, completion: (String) -> ()) {
//...
//...
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
// Now call completion to pass the value
completion(dataString)
}
And when you need to call the function you will use:
data_request("http://someapi.com/api") {
dataString in
print(dataString) // This is the string you passed to the completion
}