J'ai une fonction appelée recognDropoff et cela a bien fonctionné avec Swift 1.2 dans Xcode 6.4. Cependant, maintenant j'utilise Xcode 7.1 avec Swift 2 et j'obtiens cette erreur: Call can throw, but it is not marked with 'try' and the error is not handled
Swift 2 JSON Appel peut lancer, mais il n'est pas marqué avec 'try' et l'erreur n'est pas traitée
func recognizeDropoff() {
let currentUsername = PFUser.currentUser()!.username
let url = NSURL(string: "http://test.informatica-corlaer.nl/dropoffRecognizer.php?user=\(currentUsername!)&unique=3456364567")
let request = NSMutableURLRequest(URL: url!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if data == nil {
print("request failed \(error)")
return
}
let parseError: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {
let dropoffIndicator = json["dropoffIndicator"]
if (dropoffIndicator == "TRUE") {
dispatch_async(dispatch_get_main_queue()){
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("dropoffSuccess")
self.presentViewController(MainVC, animated: true, completion: nil)
}
}
} else {
print("parsing error: \(parseError)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
}
task.resume()
}
Le problème est dans la ligne if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String]
. Cependant, je suis assez confus parce que je viens de faire fonctionner mon code avec Swift 1.2. Je ne peux vraiment pas comprendre comment résoudre ce problème. Que devrais-je changer?
J'ai essayé toutes les autres solutions à partir d'autres questions similaires, mais je n'arrive tout simplement pas à le faire fonctionner. J'ai essayé de faire une combinaison do-catch, mais cela m'a seulement donné plus d'erreurs.
EDIT: Nouveau code que je ne peux pas comprendre
@IBAction func editingCodeChanged(sender: AnyObject) {
checkMaxLength(sender as! UITextField, maxLength: 4)
let currentUsername = PFUser.currentUser()!.username
if ((UnlockCodeField.text!).characters.count == 4) {
let url = NSURL(string: "http://test.informatica-corlaer.nl/unlockCodeTransmitter.php?user=\(currentUsername!)&unique=5782338593203")
let request = NSMutableURLRequest(URL: url!)
// modify the request as necessary, if necessary
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if data == nil {
print("request failed \(error)")
return
}
let parseError: NSError?
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {
let databaseUnlockCode = json["unlockCode"]
let enteredUnlockCode = self.UnlockCodeField.text!
if (databaseUnlockCode == enteredUnlockCode) {
dispatch_async(dispatch_get_main_queue()){
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("VehiclePurchaseStatus")
self.presentViewController(MainVC, animated: true, completion: nil)
let myUrl = NSURL(string: "http://test.informatica-corlaer.nl/VEPunlockExecuter.php?user=\(currentUsername!)&unique=8648604386910");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
print(response)
}
}
} else {
dispatch_async(dispatch_get_main_queue()){
let alert = UIAlertView()
alert.title = "Whoops!"
alert.message = "You entered the wrong code. Please enter the code displayed on the VEP screen."
alert.addButtonWithTitle("OK")
alert.show()
}
}
} else {
print("parsing error: \(parseError)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
}
task.resume()
}
}
double possible de [Comment analyser JSON à Swift 2.0 en utilisant NSURLSession] (http://stackoverflow.com/questions/31805045/how-to-parse-json-in-swift-2- 0-using-nsurlsession) – Moritz