I'm trying to convert the FBLoginCutomUISample from objective C to swift. So far everything is working fine. I just get stuck at this point:
//Get more error information from the error
NSDictionary *errorInformation = [[[error.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];
// Show the user an error message
alertTitle = @"Something went wrong";
alertText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformation objectForKey:@"message"]];
[self showMessage:alertText withTitle:alertTitle];
I tried several solutions such as:
if let info = error.userInfo {
let errorInformation = info["com.facebook.sdk:ParsedJSONResponseKey"]["body"]["error"]
let msg = errorInformation["message"]
println("errormessage: \(msg)")
}
But it gives me every time the same error: '(NSObject, AnyObject)' does not have a member named 'subscript'. It seems to be an unwrapping problem but I have no idea how to solve it. Thanks
[UPDATE SOLUTION]
From the answer below I can finally update here the working code:
if let info = error.userInfo{
if let dict1 = info["com.facebook.sdk:ParsedJSONResponseKey"] as? NSDictionary {
if let dict2 = dict1["body"] as? NSDictionary {
if let errorInformation = dict2["error"] as? NSDictionary {
if let msg:AnyObject = errorInformation["message"] {
println("errormessage: \(msg)")
}
}
}
}
}
Every dictionary lookup in Swift returns an optional that must be unwrapped. In addition, you might have to use conditional casts as?
to tell Swift what type to expect. You might be able to chain multiple dictionary accesses together by using optional chaining following each dictionary lookup with ?
.
Try this:
if let info = error.userInfo {
if let errorInformation = info["com.facebook.sdk:ParsedJSONResponseKey"]?["body"]?["error"] as? NSDictionary {
if let msg = errorInformation["message"] {
println("errormessage: \(msg)")
}
}
}
If that doesn't work, you may have to tell Swift at each step that you expect an NSDictionary
:
if let info = error.userInfo {
if let dict1 = info["com.facebook.sdk:ParsedJSONResponseKey"] as? NSDictionary {
if let dict2 = dict1["body"] as? NSDictionary {
if let errorInformation = dict2["error"] as? NSDictionary {
if let msg = errorInformation["message"] {
println("errormessage: \(msg)")
}
}
}
}
}