0

I am very much beginner in swift as well as Xcode. I am building an app in which I need to connect the sever on a particular IP and port, send a JSON request to sever and receives its response many places in code. So I want to make a global function (which can be accessible from any part of the code.) for this. I also want to implement a module (like in VB6.0) or a file which contains all the global functions and can be called where I need it.

My first question is that can I return the server response from the following function to the calling function while using httpGet function.

This function connects to the server, sends request to the sever and get the response only when the '//return abc!;' code is commented.

func connserv(jsonString:NSDictionary) -> NSDictionary{
    var abc: NSDictionary?
    // This is the action performed when clicked on the Connect button on the connectivity screen
    println("------------------Function connserv")

    let prefs = NSUserDefaults.standardUserDefaults()
    var IP: AnyObject = prefs.objectForKey("IP")!
    var port: AnyObject = prefs.objectForKey("Port")!
    println("IP in Connection : \(IP)")
    println("port in Connection : \(port)")
    prefs.synchronize()
    //var learn = LearnNSURLSession()
    let localizedModel = UIDevice.currentDevice().localizedModel
    let model = UIDevice.currentDevice().model
    let devicesystemVersion = UIDevice.currentDevice().systemVersion

    println("HTTP request jsonString : \(jsonString)")
    var request = NSMutableURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)

    var response: NSURLResponse?
    var error: NSError?

    //println("HTTP request jsonString : \(jsonString)")

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &err)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    // send the request
    var learn = LearnNSURLSession()
    println("HTTP request : \(request)")
    learn.httpGet(request) {
        (resultString, error) -> Void in
        if error != nil
        {
            println("completion block")

        }
        else
        {
            let data = (resultString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            var er: NSError?
            let JSONdata: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers,error: &er)!

            let abc: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves, error:&er)!

            println("abc : \(abc)")
            println("JSONdata : \(JSONdata)")

            learn.callback(result: resultString, error: error)
        }
    }
    //return abc!;
}

Once I uncommented the '//return abc!;' code this function does not connect to sever and does not send the request to server and gives the following error:

enter image description here

HTTP request : <NSMutableURLRequest: 0x7b99abf0> { URL: https://144.1.1.45:9299/ }
fatal error: unexpectedly found nil while unwrapping an Optional value

Please let me know how can I correct this function so that the connserv function connects to the server, sends request to the sever and returns the server response to the calling function.

Also let me know how can I make this function as global function as well as call this global function globally in the code where I need it.

Amit Raj
  • 1,358
  • 3
  • 22
  • 47

1 Answers1

0

httpGet runs asynchronously. Its completion block does not get executed until after the request completes. That means your return call is happening before you've got your object downloaded, so abc is still nil at that point, despite the fact that you've force-unwrapped it with !. You've got to pass abc via the httpGet completion block (or just handle it inside the block).

this function should already be visible to other source files in your project

Nick
  • 2,361
  • 16
  • 27
  • Please let me know should I change this function so that It works? – Amit Raj Apr 02 '15 at 05:41
  • Nick, after your reply I searched more on the internet and found the http://stackoverflow.com/questions/24647406/how-to-use-completionhandler-closure-with-return-in-swift. After going through this link. I have a doubt that can I return the server response to calling function? – Amit Raj Apr 02 '15 at 06:18