Reputation: 1699
This error is not getting fixed. Please help me out.
@IBAction func LoginButtonTapped(sender: AnyObject) {
let email = UserName.text
let password = PasswordField.text
if(password!.isEmpty || email!.isEmpty) {
return
}
let myurl = NSURL(string:"some url")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "email=\(email)&password=\(password)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err : NSError!
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as NSDictionary
if let parseJSON = json {
var resultValue:String = parseJSON["status"] as String
print("result: \(resultValue)")
if (resultValue=="success") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
task.resume()
}
I know to add this piece of code to get rectify, but I am new to iOS Swift 2.0. Don't know how to handle it.
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
Can any one help me out to add this line of code to rectify my error problem?
Upvotes: 0
Views: 91
Reputation: 71854
If you Don't care about error then Just replace
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as NSDictionary
with this:
var json = try? NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
or your code will be:
@IBAction func LoginButtonTapped(sender: AnyObject) {
let email = ""
let password = ""
if(password.isEmpty || email.isEmpty) {
return
}
let myurl = NSURL(string:"some url")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "email=\(email)&password=\(password)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
let resultValue:String = json["status"] as! String
print("result: \(resultValue)")
if (resultValue=="success")
{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
Upvotes: 1