如何从swift 4

时间:2018-03-19 16:57:51

标签: swift facebook dictionary

我正在使用Swift 4(Xcode 9)开发一个应用程序。我使用Facebook登录并获取有关我朋友的信息。 这是我的代码:

func friends() {
    let params = ["fields": "id, first_name, last_name, email, picture"]
    FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params).start { (connection, result , error) -> Void in

        if error != nil {
            print(error!)
        }
        print(result!)

        let info = result! as! [String : AnyObject]
        let info = result! as! [String : AnyObject]
        let Objet = (info as! [String : AnyObject])["data"]
        let nom = Objet!["first_name"] as! String
        print(nom)
        }
}    

但我把它们作为这样的字典:

{
data =     (
            {
        "first_name" = Sameh;
        id = AaJjv05Upw5Ly78wKWir2jfuKn5nC1PrIIccIaYFs1wclQML5l3K1qQhDekAxmVBEx1gtYEOYG7ctOFI96bv4O5irNPMvGGF9T39XnPML5CzMw;
        "last_name" = "Ben Abdallah";
        picture =             {
            data =                 {
                height = 50;
                "is_silhouette" = 0;
                url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/28379127_1987965651456087_2667061843745873769_n.jpg?oh=eb4c37b135775fea526ff8158d9ded17&oe=5B2C3F91";
                width = 50;
            };
        };
    },
            {
        "first_name" = Dhouha;
        id = "AaJrJ_bKAeZZ8JXg9twhVV0HhngwK_pUYcTEQyfvxSBJAeFg4o7oeIu9VzXQ6es_MeA1oXVRPd_sFGCq0X3Z5pi29njT_58wn6iEX1sF98tRIA";
        "last_name" = Souidi;
        picture =             {
            data =                 {
                height = 50;
                "is_silhouette" = 0;
                url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/29339568_104531293722629_3382683098066976768_n.jpg?oh=d1e4a8a3616c63327d32db670657205a&oe=5B2F734E";
                width = 50;
            };
        };
    }    

我无法将字段first_name,last_name,picture和id的值作为String获取,以便能够将它们插入到数据库中。 我收到错误:

"unexpectedly found nil while unwrapping an optional value"    

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的数据是字典。 data键为您提供了一系列词典。

您需要正确处理选项并使用正确的数据类型。

func friends() {
    let params = ["fields": "id, first_name, last_name, email, picture"]
    FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params).start { (connection, result , error) -> Void in
        if let error = error {
            print(error)
        } else if let info = result as? [String: Any] {
            print(info)
            if let data = info["data"] as? [[String: Any]] {
                for object in data {
                    if let nom = object["first_name"] as? String {
                        print(nom)
                    }
                }
            }
        } else {
            print("Unexpected result: \(String(describing: result))")
        }
    }
}