Nsurlconnection Deprecated in iOS9

NSURLConnection deprecated in iOS9

Now you have to use NSURLSession

Example (GET):

-(void)placeGetRequest:(NSString *)action withHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))ourBlock {

NSString *urlString = [NSString stringWithFormat:@"%@/%@", URL_API, action];

NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
}

Now you will need to call that method with an action (or your full URL if you prefer) and the block that will be executed when the API call return.

[self placeGetRequest:@"action" withHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// your code
}];

Inside that block, you will received a NSData with the response data and NSURLResponse with the HTTP response. So now, you can put your code there:

NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
documentsURL = [documentsURL URLByAppendingPathComponent:@"localFile.pdf"];

[data writeToURL:documentsURL atomically:YES];

Main difference between NSURLSession and NSURLConnection

  • NSURLConnection: if we have an open connection with NSURLConnection and the system interrupt our App, when our App goes to background mode, everything we have received or sent were lost.
    Process diagram for NSURLConnection

  • NSURLSession: solve this problem and also give us out of process downloads. It manage the connection process even when we don't have access. You will need to use application:handleEventsForBackgroundURLSession:completionHandler in your AppDelegate
    Process diagram for NSURLSession

So with the use of NSURLSession, you don't need to manage or to check
your internet connection because OS does it for you.

NSURLConnection was deprecated in iOS 9, How to fix it

NSURLConnection is deprecated in iOS9 just use NSURLSession instead.

In your case it will look approximately as follows:

let url = NSURL(string: urlString as String))
var task: NSURLSessionDataTask!
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let request = NSMutableURLRequest(URL: url)

task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
// Your code
})

task.resume()

IOS 9 NSURLConnection deprecated

Your actual problem is not NSURLConnection usage ios9 will handle it even if it is depricated also , here the problem with http request you are using from ios9 apple discourages the use of HTTP request as part of the App Transport Security (ATS)

From Apple documentation:

"App Transport Security (ATS) enforces best practices in the secure
connections between an app and its back end. ATS prevents accidental
disclosure, provides secure default behavior, and is easy to adopt; it
is also on by default in iOS 9 and OS X v10.11. You should adopt ATS
as soon as possible, regardless of whether you’re creating a new app
or updating an existing one.

If you’re developing a new app, you should use HTTPS exclusively. If
you have an existing app, you should use HTTPS as much as you can
right now, and create a plan for migrating the rest of your app as
soon as possible. In addition, your communication through higher-level
APIs needs to be encrypted using TLS version 1.2 with forward secrecy.

If you try to make a connection that doesn't follow this
requirement, an error is thrown. If your app needs to make a request
to an insecure domain, you have to specify this domain in your app's
Info.plist file.
"

You can bypass this by adding this key to your info.plist of the project

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

stack overflow link and blog reference link
ios9 ATS

Swift NSURLConnection deprecated in iOS 9.0

Do what the message tells you to do! Use NSURLSession instead. It replaces NSURLConnection, and is far better.

sendSynchronousRequest is deprecated in ios 9

This is a working example,
You should use NSURLSession, with Request.

     func testPost(sender: UIButton) {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let d = "4"
let data = "x=4&y=\(d)"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
print("data =\(data)")
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")

//if you response is json do the following
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
let arrayJSON = resultJSON as! NSArray
for value in arrayJSON{
let dicValue = value as! NSDictionary
for (key, value) in dicValue {
print("key = \(key)")
print("value = \(value)")
}
}

}catch _{
print("Received not-well-formatted JSON")
}
}
})
task.resume()
}

Notice it is not necessary to use the request. you can have a data task with URL, but I added the request because in your code, you have set some headers in the request.

Notice using the completionHandler which will be called when your server responses by http response.

iOS9 sendSynchronousRequest deprecated

Use NSURLSession instead like below,

For Objective-C

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response

}] resume];

For Swift,

var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["username":"username", "password":"password"] as Dictionary<String, String>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")})

task.resume()

sendAsynchronousRequest deprecated in iOS 9, how do I fix my function

Try this for

Swift 3.0

URLSession.shared.dataTask(with: request) {data, response, error in
if (error == nil) {
//Do needful things // Your code . . .
} else {
print("Error : \(error?.localizedDescription)");
}
}.resume();

NSURLConnection initWithRequest is deprecated

It seems that the whole NSURLConnection API has been deprecated in iOS 9. Existing apps will continue to work, but new builds (linked against iOS SDK) must use the newer NSURLSession API.

Ray Wenderlich has a good tutorial here.
Also, of course, check the official documentation.

When will NSURLConnection be rejected? (Not just deprecated)

tl;dr - It will probably never lead to a rejection.

NSURLConnection was only deprecated since iOS 9.0. Don't even think about it until your app's Deployment Target is iOS 9.0 or later.

Even if your Deployment Target is already iOS 9.0 or later, it is still safe to use.

There are APIs deprecated since iOS 2.0 that can still be used.

There are many, many thousands of apps in the App Store that haven't been updated in years that still use NSURLConnection. Those apps will continue to work for several years to come.

There have been extremely few deprecated APIs over the years that don't still work several iOS versions later.

I'd feel safe using NSURLConnection for a few more years if required. But plan on replacing its use in the next year. Its replacement is much better.



Related Topics



Leave a reply



Submit