sendAsynchronousRequest was deprecated in iOS 9, How to alter code to fix
Use NSURLSession
instead like below,
For Objective-C
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"]
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>
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})
task.resume()
For asynchronously query, from Apple docs
Like most networking APIs, the NSURLSession API is highly
asynchronous. It returns data in one of two ways, depending on the
methods you call:To a completion handler block that returns data to your app when a
transfer finishes successfully or with an error.By calling methods on your custom delegate as the data is received.
By calling methods on your custom delegate when download to a file is
complete.
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();
sendAsynchronousRequest deprecated in iOS 9
As the warning warns, NSURLConnection is dead. Long live NSURLSession.
let session = NSURLSession.sharedSession()
let urlString = "https://api.yoursecureapiservergoeshere.com/1/whatever"
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("done, error: \(error)")
}
dataTask.resume()
sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code?
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.
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()
Deprecated: 'sendAsynchronousRequest:queue:completionHandler:' in iOS9
dataTaskWithRequest:completionHandler:
is an instance method, not a class method. You have to either configure a new session or use the shared one:
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
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.
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
So with the use of NSURLSession, you don't need to manage or to check
your internet connection because OS does it for you.
UIAlertView is Deprecated how can i fix this code as UIAlertController? I can't figure out how to use switch statement in UIAlertController
AlertView is depricated in iOS 8.So we need to use UIAlertController.
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionAccessAddressbook = [UIAlertAction
actionWithTitle:@"Access"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[self displayFindFriendView:[NSNumber numberWithInteger: CS_CONTACTS ]];
}];
UIAlertAction *actionFindFriendEmail = [UIAlertAction
actionWithTitle:@"Find Friend Email"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//...Do your stuff here
}];
UIAlertAction *actionLogout = [UIAlertAction
actionWithTitle:@"Logout"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[self userLogout];
}];
UIAlertAction *actionClearSearchHistory = [UIAlertAction
actionWithTitle:@"ClearSearchHistory"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[[CSCoreDataHandler sharedInstance] deleteManagedObjectsInModel:@"CSRecentSearch"];
}];
[alert addAction:actionAccessAddressbook];
[alert addAction:actionFindFriendEmail];
[alert addAction:actionLogout];
[alert addAction:actionClearSearchHistory];
[self presentViewController:alert animated:YES completion:nil];
Related Topics
Multiline Uilabel with Adjustsfontsizetofitwidth
Uitextfield - Capture Return Button Event
Get iOS Itunes App Store Id of an App Itself
How to Pop Specific View Controller in Swift
When Will Applicationwillterminate Be Called
Issue with Auto Layout on iOS 8 (Code Works Perfectly on iOS 7)
Read Texture Bytes with Glreadpixels
Hide Navigationbar When Scrolling Tableview in Collectionview
Detect If Swift App Is Being Run from Xcode
How to Keep an Iphone/iPad Web App in Full Screen Mode
Space Between Sections in Uitableview
Swapping Child Views in a Container View
Accessing iOS Safari Web Inspector from Windows MAChine
How to Set Uiviewcontroller "Extend Edges" Properties