Search code examples
facebookswiftfacebook-graph-apialamofireswifty-json

Swift Alamofire Unexpectedly found nil - Facebook API


I'm running the same exact function for Instagram and Youtube API with Alamofire and SwiftyJSON; however, with Facebook's API I get fatal error: unexpectedly found nil while unwrapping an Optional value.

    var posts : [JSON] = []

    func loadFBFeed() {
    let url = "https://graph.facebook.com/mpstnews/posts/?access_token=\(apiKey)&date_format=U&fields=comments.limit(0).summary(1),likes.limit(0).summary(1),from,picture,message,story,name,link,created_time,full_picture&limit=5"

    Alamofire.request(.GET, url).responseJSON { (request, response, json) -> Void in
        switch json {
        case .Success(let data):
            let jsonObj = JSON(data)
            if let postInfo = jsonObj["data"].arrayValue as [JSON]? {
                self.posts = postInfo
                self.tableView.reloadData()
            }
        case .Failure(_, let error):
            print("Request failed with error: \(error)")
        }
    }
}

Error output


Solution

  • URL was using characters that Alamofire does not like, had to add a line to resolve...

        var urlString = "https://graph.facebook.com/mpstnews/posts/?access_token=\(apiKey)&date_format=U&fields=comments.limit(0).summary(1),likes.limit(0).summary(1),from,picture,message,story,name,link,created_time,full_picture&limit=5"
    
        urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!