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

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.

Related

I have been trying to write the Unit test cases in swift for making an API call but not able to figure out how to write

I have been trying to write Unit test cases in swift for making an API call but being new in this am not able to figure out how do I write the Unit test case for the same. here's my code for which I want to write the unit test case
class QuotesModel: ObservableObject {
#Published var quotes = [Quote]()
#MainActor
func fetchData() async {
guard let url = URL(string: "https://breakingbadapi.com/api/quotes") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
quotes = try JSONDecoder().decode([Quote].self, from: data)
} catch {
print(error)
}
// print(quotes)
}
}
I have been trying to write the unit testcase for this but am not able to figure out how do I do it. Can someone help me with this?
URLSession.shared is a singleton. There's nothing wrong with using singletons. But if you use them directly, your dependencies become hard-wired and you give up control. And URLSession is an "awkward dependency" that makes testing harder. Let's replace it.
So change your code so that it uses URLSession.shared when in production, but something else during testing — something your tests can control. Let's introduce a protocol, as I describe in https://qualitycoding.org/swift-mocking/
protocol URLSessionProtocol {
// We will add more here
}
Use an extension to make URLSession conform to this new protocol:
extension URLSession: URLSessionProtocol {}
Change your production code to use an instance of this protocol instead of directly calling URLSession.shared. But provide URLSession.shared as the default value. For example, we can add an argument to your method:
func fetchData(urlSession: URLSessionProtocol = URLSession.shared) async { … }
To make it possible to use urlSession, the protocol needs the URLSession method you use:
protocol URLSessionProtocol {
func data(for request: URLRequest, delegate: URLSessionTaskDelegate?) async throws -> (Data, URLResponse)
}
Unfortunately, we can't directly add the = nil default value for the delegate argument directly in the protocol. The easiest way to resolve this is to pass it explicitly from your calling code, which will now look like
let (data, _) = try await urlSession.data(from: url, delegate: nil)
(We could also add an extension to the protocol.)
Now test code can provide a different implementation which records how it was called. (How many times was it called? Did you use the correct URL?) And it returns canned data controlled by the test.
…All this to say: Don't write code and expect to be able to write microtests for it, as-is. This is hard. Instead, shape your code to make it easy to write microtests.

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.

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.

Pass scope to a named function, rather than a closure

I would like to separate the data processing of my NSURLSession into a separate method.
When making a URL request, I rely on the enclosing scope to provide me the user's callback.
This works:
static func makeRequest(url: String, callback: APICallback) {
let urlObject = NSURL(string: url)
var request = createRequest(urlObject!, method: "GET") // internal
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
// do some basic parsing, error checking, then...
callback(data, nil)
}
task.resume()
}
There's rather a lot of basic parsing and error checking I'd like to do at the application level, however, so I want to define and pass a function instead of a closure to the dataTaskWithRequest method:
static func makeRequest(url: String, callback: APICallback) {
let urlObject = NSURL(string: url)
var request = createRequest(urlObject!, method: "GET") // internal
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: gotResponse)
task.resume()
}
static private func gotResponse (nsdata: NSData!, response: NSURLResponse!, err: NSError!) -> Void {
// Do my parsing and handling here, instead.
// OOPS! Don't have access to the callback. :(
}
This all leads me to my question, which, despite the lengthy example, is about language features. Can I pass some captured scope to this method? In Javascript I could accomplish this using Function.prototype.bind, but I'm not sure how to do it in Swift.
This seems like a good example of when to use a curried method. Declare the function like this with a first parameter of an APICallback. Note the brackets.
static private func gotResponse(callback: APICallback)(nsdata: NSData!, response: NSURLResponse!, err: NSError!) -> Void {
// use callback: like normal
}
Then, use it like this:
var task = session.dataTaskWithRequest(request, completionHandler: gotResponse(callback))
(apologies, the syntax might not be 100% correct since your code isn’t stand alone so I can’t test it fully)
Curried functions are a little finicky and had some bugs in 1.1 (though they got fixed in 1.2), so instead of using the language support for them, you could try hand-rolling if the above doesn’t work, something like:
static private func gotResponse(callback: APICallback) -> (nsdata: NSData!, response: NSURLResponse!, err: NSError!) -> Void {
return { data, response, error in
// put the common code, capturing callback:, in here...
}
}

NSURLSession dataTaskWithRequest not being called

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.