0

I have this code here:

var credential: NSURLCredential!

    func loginUser(username: String, password: String) -> Dictionary<String, AnyObject> {

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

        credential = NSURLCredential(user:username, password:password, persistence: .ForSession)

        let requestString = NSString(format:"%@", webservice) as String
        let url: NSURL! = NSURL(string: requestString)

        var dataString: Dictionary<String, AnyObject>

        let task = session.dataTaskWithURL(url, completionHandler: {
            data, response, error in

            dispatch_async(dispatch_get_main_queue(),
            {

                do
                {
                    dataString = (try NSPropertyListSerialization.propertyListWithData(data!, options: NSPropertyListReadOptions.Immutable, format: nil)) as! Dictionary<String, AnyObject>
                }
                catch
                {
                    dataString = nil
                }

            })

        })

        task.resume()

        return dataString

    }

what I am trying to do is the following, convert the NSData to Dictionary. if it fails or if there is no data just return nill or en empty Dictionary. How would I do this?

user979331
  • 11,039
  • 73
  • 223
  • 418
  • Which parts of this function is for logging in the user and which parts are for converting the data? You should separate this into 2 functions so it's easier to understand what's happening and what you've tried – Hayden Holligan Aug 02 '16 at 17:46

1 Answers1

1

You are returning from function before your network task is finished. You should use completion block which can get called when you received response. i.e. add completion handler in your function and call it from completion block of your network service call. Refer this link for more detail

Community
  • 1
  • 1
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75