0

I have written a function which should return a certain value from a page. I have done this with JSON, so that I can get a certain value from my website. This is the function:

func getTimerData() {
    var currentUsername = PFUser.currentUser()!.username

    let url = NSURL(string: "http://dinges.informatica-dinges.nl/timerDataTransmitter.php?user=\(currentUsername!)&unique=85017438957")
    let request = NSMutableURLRequest(URL: url!)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        var parseError: NSError?
        if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? [String: String] {

            let rideTime = json["timerValue"]
            return rideTime

        }
    }
}

However, it gives me the error: Unexpected non-void return value in void function. I have tried a lot but I can't seem to find a way to fix this problem. Do you know how I can fix it?

  • `func getTimerData() -> NSTimeInterval`, or whatever is the type of `rideTime` – Jakub Vano Jan 25 '16 at 21:01
  • You can't return anything because `dataTaskWithRequest` works asynchronously. Use a completion block or a notification. – vadian Jan 25 '16 at 21:10
  • @vadian Could you please tell me how to do this? I haven't really used completion blocks or notifications yet. – Jesper Provoost Jan 25 '16 at 21:29
  • In the `Related` column there are some suggestions for example http://stackoverflow.com/questions/30279359/unexpected-non-void-return-value-in-void-function?rq=1 – vadian Jan 25 '16 at 21:31

1 Answers1

1

Declare your function with return data type as you required such as :

fun getTimerData() -> String {
    var currentUsername = PFUser.currentUser()!.username
    let url = NSURL(string: “http://dinges.informatica-dinges.nl/timerDataTransmitter.php?user=\(currentUsername!)&unique=85017438957”)
let request = NSMutableURLRequest(URL: url!)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    var parseError: NSError?
    if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? [String: String] {
        let rideTime = json["timerValue"]
        return rideTime
    }
  }
}