sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code? - ios

I'm using XCode 7.3. Here is my code:
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in}}
This works fine and my php-Script gets the string it should. But there is the
sendAsynchronousRequest was deprecated in iOS 9
message.
As I read, with Swift 2 the method has changed.
I searched a lot for this error, but I'm not able to convert the code that it matches to Swift 2. As I also read, i should use something like this
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)
but I can't get it down. And actually, I don't understand every single line. I wrote the code myself, but from some examples that it works for me.

This is the most basic way you'd use a shared session:
if let url = NSURL(string: "http://mytesturl.com"),
userField = UserTextField.text {
let request = NSMutableURLRequest(URL: url)
let bodyData = "data=" + userField
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
}
)
dataTask.resume()
}
For more detail on the other approaches including background and ephemeral sessions, as well as how to handle the NUSRLResponse, see my blogpost.

As you've found out NSURLConnection has been deprecated and NSURLSession is the new shiny.
For your example to work you still need to use the NSURL and the NSURLRequest that you have already created, and then you need an NSURLSession which you can use in various ways.
I can see that you already use the callback so in your case I assume it would be
session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
and then the important thing to remember is to call resume() on your task.
So...to translate your code I'm thinking something along those lines
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.defaultSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
task.resume()
}
You can read more about NSURL session in this tutorial from raywenderlich.com
Hope that helps

Related

URLSession is not getting timeout after specified interval in swift 3 on iOS 10

I am trying to hit a Json request in swift3 through urlsession. Request is not getting timeout after 10s
let request = NSMutableURLRequest(url: NSURL(string:url )! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0 )
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = RequestBody
let configuration =
URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10
configuration.timeoutIntervalForResource = 10
let session = URLSession(configuration: configuration, delegate: self as? URLSessionDelegate, delegateQueue:OperationQueue.main)
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in...
}
The issue is you never actually start the network request.
You need to call dataTask.resume() to actually start the request. This needs to happen right after the closure, see code below:
guard let url = URL(string: urlString) else { return }
let request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0 )
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = RequestBody
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in...
}
dataTask.resume()

How to stop task or section from NSURLSession

I am Using NSURLSession for call an post API, but when i turn of the wifi and then hit the web service and again turn on the wifi NSURLSession is calling that previously call web service, i want to stop this process. i read on some of documents that NSURLSession store the section of every service call when connection break in any situation , and again hit that service when connection established again. So now i am not getting any solution to stop that service call after connection reconnect to my device.
Any one please help me. Thanks in advance.
Below is my code i used.
let token: NSString!
let urlPath: NSURL!
if provider .isEqualToString("No"){
urlPath = NSURL(string: kAPI_SERVERBASEURL + (url as String))
}
else{
urlPath = NSURL(string: kAPI_SERVERBASEURLSEARCHPROVIDER + (url as String))
}
var postJsonData = NSData()
var jsonString = NSString()
do {
postJsonData = try NSJSONSerialization.dataWithJSONObject(dictRequest, options:[])
jsonString = NSString(data: postJsonData, encoding: NSUTF8StringEncoding)!
NSLog("request - %#", jsonString);
// do other stuff on success
} catch {
print("JSON serialization failed: \(error)")
}
let request = NSMutableURLRequest(URL: urlPath);
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
request.HTTPShouldHandleCookies = false
request.timeoutInterval = 120 ;
request.HTTPMethod = "POST";
if NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) != nil{
token = NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) as! NSString
//token = "tk_1vNoEoZRxJwY"
request.setValue("\(token)", forHTTPHeaderField: "access_token")
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postJsonData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
`
It may help you.
1.Declare one variable about the NSURLSessionTask like
var task: NSURLSessionTask? = nil
2.When ever you need to call dataTaskWithRequest assign the object to declared object like
task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))
3.when you want to cancel the request just do the below.
if nil != task {
task!.cancel()
task = nil
}
Suppose you want cancel the request before calling another one combine both 2 and 3 steps like
if nil != task {
task!.cancel()
task = nil
}
task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))

How to make CONNECT call in iOS?

NSURLSession supports POST and GET; does it also support CONNECT?
If so, what is the exact syntax?
Thanks!
Use NSMutableURLRequest to set whatever HTTP method you want
let session = NSURLSession()
guard let url = NSURL(string: "http://www.google.com") else {
fatalError("Error creating NSURL for http://www.google.com")
}
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "CONNECT"
let task = session.dataTaskWithRequest(request)
task.resume()

HTTP POST function

I'm trying to use a POST function to take text from a label and send it as an email. The problem is, whenever I try and use the text from the label, the only data in the email is []
Any ideas as to what might be wrong?
Code:
func postToServerFunction() {
var userText : String = labelText.text!
var url: NSURL = NSURL(string: "http://www.webaddress.com/email_test.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
var bodyData = userText
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)
}
}
Edit:
With this code I now get {""} in the email:
func postToServerFunction() {
var emailText = labelText
var url: NSURL = NSURL(string: "http:www.webaddress.com/email_test.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
var bodyData = "\(emailText)"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)
}
}
This API is deprecated in iOS9. Probably the easiest way to do this is by using Alamofire (https://github.com/Alamofire/Alamofire)
If you still wanted to use this API, then you should use the 'data' object.
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
let strData = String(data, NSUTF8StringEncoding)
print(strData)
}
so this way you are initiating string instance from the NSData returned.
Please don't use NSURLConnection, as noted by other it's deprecated. If you don't want to depend on external libraries (Alamofire) use NSURLSession instead.
guard let url = NSURL(string: "http://www.webaddress.com/email_test.php") else {
print("bad url")
return
}
let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
let request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
request.HTTPBody = "Some Text".dataUsingEncoding(NSUTF8StringEncoding);
let post = session.dataTaskWithRequest(request) { data, response, error in
guard let data = data, let response = response where error == nil else {
print("Connection error")
return
}
let strData = String(data, NSUTF8StringEncoding)
print(strData)
}
post.resume()

POST Connection from swift2 IOS to PHP

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

Resources