简体   繁体   English

如果有数据填充字典,则为Swift,如果不为零

[英]Swift if there is data populate Dictionary, if not nill

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. 我想做的是以下操作,将NSData转换为Dictionary。 if it fails or if there is no data just return nill or en empty Dictionary. 如果失败或没有数据,则返回nill或空的Dictionary。 How would I do this? 我该怎么做?

You are returning from function before your network task is finished. 您正在从网络上完成网络任务之前返回。 You should use completion block which can get called when you received response. 您应该使用完成块,当您收到响应时可以调用它。 ie add completion handler in your function and call it from completion block of your network service call. 即在您的函数中添加完成处理程序,然后从您的网络服务调用的完成块中调用它。 Refer this link for more detail 请参阅此链接以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM