NSURLSession dataTaskWithRequest not being called - swift

I have a second NSURLSession that is being called directly from the completionHandler of the previous one (it is dependent on the cookies generated from the first call). It worked for a while and sometimes still works, but most of the time does not. When I set through the debugger, it simply goes from the dataTaskWithRequest line to the line past the task.resume() call. Any thoughts?
func getDates () -> [NSDate] {
var urlDays = NSURL(string: "https://mycorrecturl.com")
var requestDays = NSMutableURLRequest(URL: urlDays!)
let sessionDays = NSURLSession.sharedSession()
// Create array of NSDate objects
var allDates = [NSDate]()
var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in
// Convert into array of NSDate objects
})
task.resume()
return allDates
}
Why would this this dataTaskWithRequest function just not fire?

The problem that you are facing is that dataTaskWithRequest is an asynchronous call, that's the reason why you receive an empty array (that's only chance that finish and return a the same time and sometimes you receive data).
For that, you need to use a closure that get's call from the closure of dataTaskWithRequests.
Like this (here I only show you the declaration method with a closure):
func getDates (success:([NSDate])->Void){
And in the body of your network call:
var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in
// Convert into array of NSDate objects
var yourArrayOfNSDateConverted:[NSDate] = [NSDate]()
success(yourArrayOfNSDateConverted)
})
Obviously the yourArrayOfNSDateConverted contains your process the data and also you need to manage the error (for that you can add another closure).

Looks like it is firing, I just wasn't waiting long enough. The function returned back to the calling function with no data, but thats because the NSURLSession wasn't finished yet. I guess I'm still getting the hang of the asynchronous nature of NSURLSession.

Related

Access dataTask from inside completionHandler

I am using URLSession.shared.dataTask(with:completionHandler:) to access an API which, on certain circumstances, won't respond immediately. I also need to cancel pending requests on certain conditions.
My current implementation uses the completionHandler approach and multiple requests can happen in parallel. This makes it very inconvenient to change the pattern to a delegate.
What I am trying is to store every pending task in a set, and then remove the task from the set once they are done. The problem is accessing the return of the dataTask from inside the completion handler seems very cumbersome, to a point I am not sure this is even correct.
class API {
private var tasks: Set<URLSessionTask> = []
func sendRequest(path: String, body: [String: Any], completionHandler: #escaping #Sendable (APIResponse) -> Void) {
var request = // ... create request
let task = URLSession.shared.dataTask(with: request) { [self] data, response, error in
// ... handle response
tasks.remove(task)
}
tasks.insert(task)
task.resume()
}
func cancelAllTasks() {
for task in tasks {
task.cancel()
tasks.remove(task)
}
}
}
I either get a compiler error Closure captures 'task' before it is declared or a warning 'task' mutated after capture by sendable closure.
Is there a better way of doing this?
The problem is that your completion handler tries to reference the task which isn't yet defined when you create the completion handler.
Assuming your requests are unique, you could use a dictionary of your data tasks keyed by their URLRequest. Then add a method taskComplete(forRequest:) to your API class. Have your completion handler send that message to the API class.
The API class could remove the task using the request as a key (I checked. URLRequest is Hashable.
If your requests aren't certain to be unique, create a request struct that contains the URLTask and the Date when the task is created. The Date should make the hash of the request struct unique.

Swift POST Request in same Thread

Hope you can help me. I want a swift function that make a post request and return the json data
so here is my class
import Foundation
class APICall {
//The main Url for the api
var mainApiUrl = "http://url.de/api/"
func login(username: String, password: String) -> String {
let post = "user=\(username)&password=\(password)";
let action = "login.php";
let ret = getJSONForPOSTRequest(action: action, post: post)
return ret;
}
//Function to call a api and return the json output
func getJSONForPOSTRequest(action: String, post: String) -> String {
var ret: String?
let apiUrl = mainApiUrl + action;
let myUrl = URL(string: apiUrl);
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = post;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
print("response=\(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let login = parseJSON["Login"] as? String
print("login: \(login)")
ret = login
}
} catch {
print(error)
}
}
task.resume()
return ret!;
}
}
But ret is nil. In the debugger is see the inner of the task is called later by another thread?
How can if fix that?
Thank you guys
The data task completion closure is called on another thread and after the execution of the method is completed so you need to re-jig your code a bit. Instead of having a String return value for your getJSONForPOSTRequest, don't return anything and instead have an additional argument that is a closure and call that from within your dataTask closure instead.
func getJSONForPOSTRequest(action: String, post: String, completion: (string: String) -> Void) {
// ...
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// ... (Convert data to string etc.)
completion(string: myString)
}
task.resume()
}
Remember, doing this means that the completion handler will be called once the network request completes and not right away.
EDIT:
Lets take this from the beginning. When you download something from the network in iOS you typically use NSURLSession. NSURLSession has a number of methods available to it for different means of interacting with the network, but all of these methods use a different thread, typically a background thread, which will do work independently of the rest of your code.
With this in mind, when you call the dataTask method you will notice that you have to add a completion closure as one of the parameters (notice in your example you are using something called a 'trailing closure' which is a closure that is the last argument in the method call that doesn't fall within the parenthesis of the method with the rest of the arguments). Think of a closure as a piece of code that is executed at a different time, it's not executed in line with the rest of the code around it (See the Swift documentation on closures here). In this case the closure will be called once the network request has been completed. Network requests aren't instant so we typically use a background thread to execute them while the user is shown an activity indicator etc and can still use the app. If we waited until the network request completed on the same thread as the rest of our code then it results in the app appearing laggy and even frozen which is terrible for users.
So going back to your example at hand; when you call your getJSONForPOSTRequest method the code within that method will complete and return before the network request has completed which is why we don't need to use a return value. Once the network request has completed your closure code will get called. Because the closure is called later it's also being called from an entirely different place within the code, in this case it's called from within iOS's network code. Because if this if you return a value from within the closure you will be trying to return the value to the network code which isn't what you want, you want to return the value to your own code.
To return the value of the network response to your code you need to define a closure (or a delegate, but I'm not going to go into that here) yourself. If you look at the example code above I've removed the return value from your getJSONForPOSTRequest method and added a new argument called 'completion', and if you look at the type of that argument you can see it's (string: String) -> Void, this defines a closure that passes in a string (the string that you will have downloaded from the network). Now that we have a closure thats within your method we can use this to call back to the caller of the getJSONForPOSTRequest with the data we have downloaded form the network.
Lets take your login method and see how we use getJSONForPOSTRequest within it:
func login(username: String, password: String, completion: (success: Bool) -> Void) {
let post = "user=\(username)&password=\(password)";
let action = "login.php";
let ret = getJSONForPOSTRequest(action: action, post: post) { string in
// This will be called once the network has responded and 'getJSONForPOSTRequest' has processed the data
print(string)
completion(success: true)
}
}
See that again we aren't returning anything directly from the login method as it has to rely on the a-synchronousness of calling off to the network.
It might feel by now that you are starting to get into something called 'callback hell', but this is the standard way to deal with networking. In your UI code you will call login and that will be the end of the chain. For example here is some hypothetical UI code:
func performLogin() {
self.activityIndicator.startAnimating()
self.apiCaller.login(username: "Joe", password: "abc123") { [weak self] success in
print(success)
// This will get called once the login request has completed. The login might have succeeded of failed, but here you can make the decision to show the user some indication of that
self?.activityIndicator.stopAnimating()
self?.loginCompleted()
}
}
Hopefully that clarifies a few things, if you have any other questions just ask.

What exactly does a closure do when retrieving data from a server?

I watched a video on closures and someone demonstrated the basics of closures in this way:
func outer(howMuch: Int) -> () -> Int {
var total = 0
inner() {
howMuch += total
return total
}
return inner
}
He then went on to say that when you do this:
let incrementBy10 = outer(10)
he said that incrementBy10 references the inner() function inside the closure.
Then he proceeds with a practical example with retrieving data:
let url = "*url here*"
let nsURL = NSURLSession.shareSession().dataTaskWithUrl(nsURL) {(data,response,error) in
print(NSString(data: data, encoding: NSUTF8StringEncoding)) }
How does the 'incrementby10' example relate to the practical example of fetching some data from a server. I did not understand what he meant by: "when you grab something from a url, you are not gonna have the content immediately. You can call the closure when the url has been downloaded."
This is an example of an asynchronous callback.
Asynchronous callbacks are used to execute a closure when a long-running operation (e.g. a network request) has finished. They allow us to fire the network request, passing in the callback, then continuing executing other code while the network operation is in progress. Only when the operation finishes, the closure is executed, with the data returned by the server passed in as an argument.
If we didn't use asynchronous closures, when we fetch something from the server, the app would freeze (execution would stop). This would be a synchronous network request, and it is not used as it would lead to a very laggy UI and a horrible user experience.
NSURLSession's dataTaskWithURL is by nature an asynchronous API, it accepts a closure as an argument and fires it when a response is received.
Asynchronous Callback
Example of an asynchronous callback network call (add it to a Swift Playground):
import UIKit
import XCPlayground // Only needed for Playground
// Only needed for Playground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
class HTTP {
class func GET(onSuccess: NSData -> Void ) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://httpbin.org/get")!, completionHandler: { data, response, error in
onSuccess(data!)
}).resume()
}
}
print("About to fire request")
HTTP.GET({ payload in
let response = NSString(data: payload, encoding: NSUTF8StringEncoding)
print("Got network response: \(response)")
})
print("Just fired request")
The result that is printed is not what you might expect intuitively:
About to fire request
Just fired request
Got network response: ...
Just fired request is printed before Got network response: ... because the network request is performed asynchronously.
A synchronous version of the above code would produce the following output:
About to fire request
Got network response: ...
Just fired request

Passing an object out of a response handler

Please help me understand why I cannot alter / pass an object out of an http request. In below example I have declared variable 'someVar' and have altered it within the request handler. However the print statement returns 5 both in the init and at the end of the function.
var someVar = 5
init () {
getHtml()
print(self.someVar)
}
func getHtml() {
Alamofire.request(.GET, "https://www.google.com/")
.response { (request, response, data, error) in
self.someVar = 10
}
print(self.someVar)
}
Questions:
Why doesn't it print out a '10' in both cases?
How do I alter an object within the request handler?
I apologize ahead of time for bad terminology or if this is a strange question. I am new to Swift and this is my first Stack Overflow question.
1) It doesn't print "10" because in both cases
print(self.someVar)
is executed BEFORE
self.someVar = 10
This is because your request is an asynchronous one. This means that it will return whenever it finishes and will trigger a completion block that you specified. However, this request is not blocking your code and so next line is executed immediately.
2) The way you alter your object is correct and is working. It is just that you do not see the result because both of your print() are called before the object is altered. Change you code to:
var someVar = 5
init () {
getHtml()
}
func printVar() {
print("My variable is now \(self.someVar)")
}
func getHtml() {
Alamofire.request(.GET, "https://www.google.com/")
.response { (request, response, data, error) in
self.someVar = 10
self.printVar()
}
print("My variable is still \(self.someVar)")
}
Run this code and you will see that first you get a line "My variable is still 5" and then after some delay you will get "My variable is now 10". I hope this will help you to understand how completion handlers in asynchronous requests work.
I have put the second print() into a separate function to illustrate how you can call some function to notify your class that request has returned and it is now possible to use the data which came with it.

(Swift) String if not convertible to void [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I`m trying to make a http-get-request function but it still now working.
http://i.stack.imgur.com/8hge2.png
But if I do like there, function returns an empty result
http://i.stack.imgur.com/CTCt4.png
What`s wrong with that?
The function you are calling has the following prototype :
func dataTaskWithRequest(
_ request: NSURLRequest,
completionHandler completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void
) -> NSURLSessionDataTask?
It means the completionHandler closure don't have to return something. So it's normal it's saying you that String is not convertible to Void.
What you are expecting is calling a synchronous method expecting it to return when the asynchronous call inside is finished. It's possible but I don't think that's the way you want to do it (it might block the UI).
If you want this code to run as I think you expect it to work you need to change httpGet: to be able to pass a completionHandler too that will be called by the completionHandler of dataTaskWithRequest.
Like this :
func httpGet(url: String, completion: String -> Void) {
var googleUrl = NSURL(string: url)
var request = NSMutableURLRequest(URL: googleUrl!)
request.HTTPMethod = "GET"
request.addValue("text/html", forHTTPHeaderField: "Content-Type")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if error != nil {
println(error.localizedDescription)
}
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String)
})
task.resume()
}
Please note this code is not safe at all (force unwrapping and too few checks) but it sums up how you should structure your code.
To use it somewhere you can do as follows :
Let's imagine you have a label Outlet.
httpGet("http://someurl.com") { result in
label.text = result
}
The text attribute of label will be set as soon as the async call finished.
first you are using a closure, look at the meaning of this:
{()->void in
return // the closure returns a void
}
you are using async request, so you need to do a call back function.
if you are familiar with javascript, I think this is a great explanation about how async works.