Hi guys i have been stuck in this problem for nearly 2 week
The Problem is that i am getting the error fatal Error Unexpectedly while unwrapping an optional value while i am loading comments..
I am trying to load JSON data For the Comments
in PopularShotsCollectionViewController
import UIKit
import FMMosaicLayout
private let reuseIdentifier = "Cell"
class PopularShotsCollectionViewController: UICollectionViewController {
private var shots : [Shot] = [Shot](){
didSet{
self.collectionView?.reloadData()
}
}
var API_URL = Config.SHOT_URL
var shotPages = 1
var shot : Shot!
var comments : [Comment] = [Comment]()
var tableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let layout : FMMosaicLayout = FMMosaicLayout()
self.collectionView?.collectionViewLayout = layout
// Do any additional setup after loading the view.
self.title = "Popular"
self.API_URL = Config.POPULAR_URL
self.loadShots()
self.loadComments()
}
func loadComments(){
// When i debug shot.commentsUrl does not return nil
DribbleObjectHandler.getComments(shot.commentsUrl) { (comments) -> Void in
self.comments = comments
}
}
But i am getting this error:
The code for the getCommentsMethod
class func getComments(commentsUrl : String, completion:(([Comment]) -> Void)) {
var comments = [Comment]()
let url = commentsUrl + "&access_token=" + Config.ACCESS_TOKEN
HttpService.getJSON(url) { (jsonData) -> Void in
for commentData in jsonData {
let comment = Comment(data: commentData as! NSDictionary)
comments.append(comment)
}
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0), { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(comments)
})
})
}
}
Code for the HttpService
import Foundation
import UIKit
import Alamofire
class HttpService {
class func getJSON(url: String, callback:((NSArray) -> Void)) {
let nsURL = NSURL(string: url)!
Alamofire.request(.GET, nsURL).response { (request, response, data, error) -> Void in
if error != nil{
print("error")
}
if data != nil {
let jsonData = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSArray
print(jsonData)
callback(jsonData)
}
}
}
}
If you need more Code to solve the problem i am more than happy
And in PopularShotsCollectionViewController i have been loading shots also
with the same method
func loadShots(){
DribbleObjectHandler.getShots(API_URL) { (shots) -> Void in
self.shots = shots
}
}
but i get no error and it works perfectly
and code for the get Shots is same.. Just we access The Shot class in loadShots and we access The Comment Class in loadComments
The Comment Class
import Foundation
import UIKit
class Comment {
var id : Int!
var body : String!
var date : String!
var user : User!
init(data : NSDictionary){
self.id = data["id"] as! Int
let bodyHTML = Utils.getStringFromJSON(data, key: "body")
self.body = Utils.stripHTML(bodyHTML)
let dateInfo = Utils.getStringFromJSON(data, key: "created_at")
self.date = Utils.formatDate(dateInfo)
if let userData = data["user"] as? NSDictionary {
self.user = User(data: userData)
}
}
}
Code for the Shot Class
import Foundation
class Shot: DribbbleBase {
var imageUrl : String!
var htmlUrl : String!
var commentsUrl : String!
var bucketsUrl : String!
var likesUrl : String!
var attachmentUrl : String!
var reboundUrl : String!
var title : String!
var date : String!
var description : String!
var commentCount : Int!
var viewsCount : Int!
var likesCount : Int!
var bucketsCount : Int!
var attachmentsCount : Int!
var reboundCount : Int!
var user : User!
override init(data: NSDictionary) {
super.init(data: data)
self.commentCount = data["comments_count"] as! Int
self.likesCount = data["likes_count"] as! Int
self.viewsCount = data["views_count"] as! Int
self.bucketsCount = data["buckets_count"] as! Int
self.attachmentsCount = data["attachments_count"] as! Int
self.reboundCount = data["rebounds_count"] as! Int
self.commentsUrl = Utils.getStringFromJSON(data, key: "comments_url")
self.bucketsUrl = Utils.getStringFromJSON(data, key: "buckets_url")
self.likesUrl = Utils.getStringFromJSON(data, key: "likes_url")
self.title = Utils.getStringFromJSON(data, key: "title")
self.attachmentUrl = Utils.getStringFromJSON(data, key: "attachments_url")
self.reboundUrl = Utils.getStringFromJSON(data, key: "rebounds_url")
let dateInfo = Utils.getStringFromJSON(data, key: "created_at")
self.date = Utils.formatDate(dateInfo)
let desc = Utils.getStringFromJSON(data, key: "description")
self.description = Utils.stripHTML(desc)
let images = data["images"] as! NSDictionary
self.imageUrl = Utils.getStringFromJSON(images, key: "normal")
//let tags = data["tags"] as! NSArray
if let userData = data["user"] as? NSDictionary {
self.user = User(data: userData)
}
}
}
and Code for DribbbleBase
import Foundation
class DribbbleBase {
var id: Int
init(data: NSDictionary){
self.id = data["id"] as! Int
}
}
Please help me.. And Please Bear in mind i am fairly new to Swift
Thanks in Advance
Aryan
you declared shot property in your PopularShotsCollectionViewController and you didn't initialize it so shot is be nil. Then you tried to access commentsUrl property of shot which is nil in the loadComments method. You should instantiate shot in the init or view did load method of your view controller
Related
I try to send the voting from users to firebase and save them under the specific user.
class User: NSObject {
var id: String?
init(dictionary: [String: AnyObject]) {
self.id = dictionary["id"] as? String
}
var ref: DatabaseReference!
var numberOfGood = 0
init(id: String? = nil) {
self.id = id
ref = Database.database().reference().child("users").childByAutoId()
}
init(snapshot: DataSnapshot){
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
numberOfGood = value["numberOfGood"] as! Int
}
}
func save() {
let postDictionary = [
"id" : self.id,
"numberOfGood" : self.numberOfGood,
] as [String : Any]
self.ref.setValue(postDictionary)
}
}
Inside the viewController where to vote I handle the voting itself like this:
class UserRatingClass {
var numberOfGood = 0
var ref = Database.database().reference().child("users").childByAutoId()
func good() {
numberOfGood += 1
ref.child("numberOfGood").setValue(numberOfGood)
}
}
var userRating: UserRatingClass! {
didSet {
let x = userRating.numberOfGood
self.good.setTitle("\(x) 👍", for: [])
}
}
#IBAction func goodReview(_ sender: UIButton) {
userRating.good()
let x = userRating.numberOfGood
self.good.setTitle("\(x) 👍", for: [])
}
I tried different ways like
var StringGood = String(user?.numberOfGood)
self.ref.child("users").child(StringGood).setValue(x)
inside the buttonActionFunction but by this I'm always getting Cannot invoke initializer for type 'String' with an argument list of type '(Int?)' as an error...
Edit: I call the User.swift class like this:
var user: User?
I have problem with use data from firebase after get them. I written function getData() in model, use delegate to call them on UITableViewController and set data to TableView.
But when I create new array to get data from func getData(), this array is nil.
This is my model:
import Foundation
import Firebase
protocol myDelegate: class {
func didFetchData(datas: [Book])
}
class Book {
var Id: String?
var Author: String?
var ChapterCount: Int?
var CoverPhoto: String?
var Genre: String?
var Image: String?
var Intro: String?
var Like: Int?
var Name: String?
var Status: String?
var UpdateDay: String?
var UploadDay: String?
var View: Int?
var ref: DatabaseReference!
weak var delegate: myDelegate?
init()
{
}
init(Id: String,Author: String,Image: String,Name: String,Status: String,UpdateDay: String,View: Int)
{
self.Id = Id
self.Author = Author
self.Image = Image
self.Name = Name
self.Status = Status
self.UpdateDay = UpdateDay
self.View = View
}
func getListBook() {
ref = Database.database().reference()
ref.child("Book").observe(.value, with: { snapshot in
var newNames: [Book] = []
let value = snapshot.value as? NSDictionary
for nBook in value! {
let val = nBook.value as? NSDictionary
self.Name = val?["Name"] as? String ?? ""
self.Author = val?["Author"] as? String ?? ""
self.View = val?["View"] as? Int ?? 0
self.Status = val?["Status"] as? String ?? ""
self.Id = val?["Id"] as? String ?? ""
self.Image = val?["Image"] as? String ?? ""
self.UpdateDay = val?["UpdateDay"] as? String ?? ""
newNames.append(Book(Id: self.Id!, Author: self.Author!, Image: self.Image!, Name: self.Name!, Status: self.Status!, UpdateDay: self.UpdateDay!, View: self.View!))
}
self.delegate?.didFetchData(datas: newNames)
})
}
}
And there is class UITableViewController:
import Firebase
class ListStoryTableView: UITableViewController, myDelegate {
var ref: DatabaseReference!
var book = Book()
var listBook: [Book] = []
func didFetchData(datas: [Book]) {
listBook = datas
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib.init(nibName: "ListStoryTableViewCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "ListStoryTableViewCell")
book.delegate = self
book.getListBook()
print("\(listBook)") //this is return 0
}```
One solution would be to change-remove your protocol implementation and use a completion block in your getListBook func. Delete myDelegate reference from your ListStoryTableView and do the following change:
func getListBook(completion: #escaping (_ books: [Book]) -> Void) {
ref = Database.database().reference()
ref.child("Book").observe(.value, with: { snapshot in
var newNames: [Book] = []
let value = snapshot.value as? NSDictionary
for nBook in value! {
let val = nBook.value as? NSDictionary
self.Name = val?["Name"] as? String ?? ""
self.Author = val?["Author"] as? String ?? ""
self.View = val?["View"] as? Int ?? 0
self.Status = val?["Status"] as? String ?? ""
self.Id = val?["Id"] as? String ?? ""
self.Image = val?["Image"] as? String ?? ""
self.UpdateDay = val?["UpdateDay"] as? String ?? ""
newNames.append(Book(Id: self.Id!, Author: self.Author!, Image: self.Image!, Name: self.Name!, Status: self.Status!, UpdateDay: self.UpdateDay!, View: self.View!))
}
completion(newNames)
})
}
and then in your viewDidLoad or any other function you use the following to fetch your data:
book.getListBook { books in
listBook = books
tableView.reloadData()
}
I hope that helps you.
func didFetchData(datas: [Book]) {
listBook = datas
print("\(listBook)")
}
print listBook in this function and you will have the data..
I have a database with some tables, each table represents a object of my project. I want write a generic function to read, by SQL, a table and create a object with the records readed. So, the parameters of my function are: Table Name and Object Type. The code below is my func to do this. In the end of func, I tries call what I would like to do, but with a especific object, that's don't the I want.
func readAll<T>(objeto: String, typeClass: T.Type) -> [T] {
var ret : [T] = []
// STATEMENT DATA
let queryString = "SELECT * FROM \(objeto);"
var queryStatement: OpaquePointer? = nil
// STATEMENT DATA TYPE
let queryString2 = "PRAGMA table_info(\(objeto));"
var queryStatement2: OpaquePointer? = nil
// 1
if sqlite3_prepare_v2(db,queryString,-1,&queryStatement,nil) != SQLITE_OK {
print("Error to compile readAll \(objeto) 1")
return ret
}
if sqlite3_prepare_v2(db,queryString2,-1,&queryStatement2,nil) != SQLITE_OK {
print("Error to compile readAll \(objeto) 2")
return ret
}
var listNameColumns : [String] = []
while( sqlite3_step(queryStatement2) == SQLITE_ROW ) {
listNameColumns.append( String(cString: sqlite3_column_text(queryStatement2, 2)!) )
}
// 2
while ( sqlite3_step(queryStatement) == SQLITE_ROW ) {
var dict: [String:Any] = [:]
for i in 0...listNameColumns.count-1 {
let nameColumn = String(cString: sqlite3_column_name(queryStatement,Int32(i))!)
switch (sqlite3_column_type(queryStatement, Int32(i))) {
case SQLITE_TEXT:
dict[nameColumn] = String(cString: sqlite3_column_text(queryStatement, Int32(i))!)
break
case SQLITE_INTEGER:
dict[nameColumn] = sqlite3_column_int(queryStatement, Int32(i))
break
case SQLITE_FLOAT:
dict[nameColumn] = sqlite3_column_double(queryStatement, Int32(i))
break
default:
print("Tipo desconhecido.")
break
}
}
ret.append(ResPartner(dict: dict)) <------ HERE IS MY QUESTION!
}
// 3
sqlite3_finalize(queryStatement2)
sqlite3_finalize(queryStatement)
return ret
}
Here are two objects, They are a bit different, but the builder works the same and the fields as well.
class ResPartner {
static let fieldsResPartner : [String] = ["id","company_type_enum_for_customer","name","contact_address","customer_account_number","customer_group_id","segment_id","subsegment_id","economic_group_id","street","category_id","type_stablishment_id","final_user","final_taxpayer","cnpj_cpf","inscr_est","ccm","cnae","phone","phone_extension","mobile","fax","email","email_extra","website","lang"]
var attributes : [String:Any] = [:]
init(dict : [String:Any]) {
for k in dict.keys {
if(ResPartner.fieldsResPartner.contains(k)) {
attributes[k] = dict[k]
}
}
}
func toString() {
for k in attributes.keys{
print("\(k) - \(attributes[k]!)")
}
}
}
class Product {
static let fieldsProducts : [String] = ["id","name","default_code","display_name","categ_id","company_ax_id","destination_type","fiscal_class_code","multiple","taxes_id","uom_id","uom_po_id","__last_update","active","create_date","create_uid","currency_id","invoice_police","item_ids","list_price","price","pricelist_id","type"]
public var default_code: String!
public var display_name: String!
public var id: Int!
public var name: String!
public var destination_type: String!
public var company_ax_id: Int!
public var categ_id: Int!
public var fiscal_class_code: String!
public var taxes_id: Int!
public var uom_id: Int!
public var uom_po_id: Int!
public var multiple: Int!
public var last_update: String!
public var active: Bool!
public var create_date: String!
public var create_uid: Int!
public var currency_id: Int!
public var invoice_police: String!
public var item_ids: [Int]!
public var list_price: String!
public var price: Float!
public var pricelist_id: Int!
public var type: String!
init() {
}
init( dict : [String:Any] ) {
self.default_code = dict["default_code"] as! String
self.display_name = dict["display_name"] as! String
self.id = dict["id"] as! Int
self.name = dict["name"] as! String
self.destination_type = dict["destination_type"] as! String
self.company_ax_id = dict["company_ax_id"] as! Int
self.categ_id = dict["categ_id"] as! Int
self.fiscal_class_code = dict["fiscal_class_code"] as! String
self.taxes_id = dict["taxes_id"] as! Int
self.uom_id = dict["uom_id"] as! Int
self.uom_po_id = dict["uom_po_id"] as! Int
self.multiple = dict["multiple"] as! Int
self.last_update = dict["last_update"] as! String
self.active = dict["active"] as! Bool
self.create_date = dict["create_date"] as! String
self.create_uid = dict["create_uid"] as! Int
self.currency_id = dict["currency_id"] as! Int
self.invoice_police = dict["invoice_police"] as! String
self.item_ids = dict["item_ids"] as! [Int]
self.list_price = dict["list_price"] as! String
self.price = dict["price"] as! Float
self.pricelist_id = dict["pricelist_id"] as! Int
self.type = dict["type"] as! String
}
}
So, my question is, How I call the constructor of T.Type class passed by parameter? I did read about protocols, extensions, other posts, but not solves my problem.
You can constrain your generic with protocol:
Define a protocol for initializing with a dictionary:
protocol DictionaryInitializable {
init(dict: [String: Any])
}
Make your two types conform to that type (you'll have to add required to your init methods, as prompted by Xcode), e.g.:
class Product: DictionaryInitializable {
...
required init(dict: [String: Any]) {
...
}
}
and
class ResPartner: DictionaryInitializable {
static let fieldsResPartner = ...
var attributes: [String: Any] = [:]
required init(dict: [String: Any]) {
for k in dict.keys where ResPartner.fieldsResPartner.contains(k) {
attributes[k] = dict[k]
}
}
func toString() { ... }
}
Change your method declaration to make it clear that T must conform to your new protocol:
func readAll<T: DictionaryInitializable>(objeto: String, typeClass: T.Type) -> [T] {
var ret: [T] = []
...
// 2
while ( sqlite3_step(queryStatement) == SQLITE_ROW ) {
var dict: [String: Any] = [:]
...
ret.append(T(dict: dict)) // You can now use `T` here
}
return ret
}
And you’d call it like:
let list = db_respartner.readAll(objeto: "res_partner", typeClass: ResPartner.self)
Create a Protocol with init Method
protocol Mappable {
init(dictionary:[String:AnyObject]) // Changed based on your requirement.
}
Conform your protocol in ResPartner.
class ResPartner: Mappable {
required init(dictionary : [String : AnyObject]) {
// initialize here
}
}
Conform your protocol in Product.
class Product: Mappable {
required init(dictionary : [String : AnyObject]) {
// initialize here
}
}
Create a custom objects
func readAll<T:Mappable>(objeto: String, typeClass: T.Type) -> [T] {
var ret : [T] = []
// intialize your variable
let obj = typeClass.init(dictionary: ["":"" as AnyObject])
return ret
}
I am trying to grab a list of bars from a Firebase Database and store it in an array so I can display it in a table view.
I have configured Firebase and managed to get data in the app as String, AnyObject dictionary.
Here is my code :
struct Bar {
var latitude: Double?
var longitude: Double?
var name: String!
var phoneNumber: String?
var happyHour: String?
var url: NSURL?
var barLogo: UIImage?
var followers: Int?
var addedToFavorites: Int?
var zipCode: Double?
var area: String?
}
class ViewController: UIViewController {
var ref: FIRDatabaseReference!
var refHandle: UInt!
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
refHandle = ref.observe(FIRDataEventType.value , with: {(snapshot) in
let dataDict = snapshot.value as! [String : AnyObject]
}
)
}
Here is my JSON exported from Firebase:
{
"data" : {
"bars" : {
"bar1" : {
"addedToFavorites" : 0,
"area" : "upper east",
"follwers" : 0,
"happyHour" : "m-f 16-19",
"lattitude" : 4412334,
"longitude" : 223455,
"name" : "bar1",
"phone" : 212222,
"url" : "http://www.bar1.com",
"zipCode" : 12345
},
"bar2" : {
"addedToFavorites" : 0,
"area" : "upper west",
"follwers" : 0,
"happyHour" : "f - s 20-22",
"lattitude" : 4443221,
"longitude" : 221234,
"name" : "bar 2",
"phone" : 215555,
"url" : "http://www.bar2.com",
"zipCode" : 54321
}
}
}
}
What would be the best approach for this?
I would like to scale it and download hundreds of bars, so manually grabbing the data from the dictionary and storing it into a Bar struct variable and then appending it to an array is not a path I want to go on.
I need a solution to grab all the bars and somehow adding them to an array (or any other method to display them into a tableView).
Thanks in advance.
I found a way to solve this issue :
First of all I got rid of the struct and created a class :
My class file :
import Foundation
import UIKit
class Bar {
private var _name: String!
private var _area: String!
private var _latitude: Double!
private var _longitude: Double!
private var _followers: Int!
private var _happyHour: String!
private var _phone: Double!
private var _url: String!
private var _zipCode: Double!
private var _addedToFav: Int!
var name: String! {
return _name
}
var area: String! {
return _area
}
var latitude: Double! {
return _latitude
}
var longitude: Double! {
return _longitude
}
var followers: Int! {
return _followers
}
var happyHour: String! {
return _happyHour
}
var phone: Double! {
return _phone
}
var url: String! {
return _url
}
var zipCode: Double! {
return _zipCode
}
var addedToFav: Int! {
return _addedToFav
}
init(name: String,area: String! , latitude: Double, longitude: Double, followers: Int, happyHour: String, phone: Double, url: String, zipCode: Double, addedToFav: Int) {
self._name = name
self._area = area
self._latitude = latitude
self._longitude = longitude
self._followers = followers
self._happyHour = happyHour
self._phone = phone
self._url = url
self._zipCode = zipCode
self._addedToFav = addedToFav
}
init(barData: Dictionary<String, AnyObject>) {
if let name = barData["name"] as? String {
self._name = name
}
if let area = barData["area"] as? String {
self._area = area
}
if let latitude = barData["lattitude"] as? Double {
self._latitude = latitude
}
if let longitude = barData["longitude"] as? Double {
self._longitude = longitude
}
if let followers = barData["followers"] as? Int {
self._followers = followers
}
if let happyHour = barData["happyHour"] as? String {
self._happyHour = happyHour
}
if let phone = barData["phone"] as? Double {
self._phone = phone
}
if let url = barData["url"] as? String {
self._url = url
}
if let zipCode = barData["zipCode"] as? Double {
self._zipCode = zipCode
}
if let addedToFav = barData["addedToFavorites"] as? Int {
self._addedToFav = addedToFav
}
}
}
I created a DataService class with a singleton
Data service class file:
import Foundation
import Firebase
let URL_BASE = FIRDatabase.database().reference()
class DataService {
static let ds = DataService()
private var _REF_BASE = URL_BASE
private var _REF_BARS = URL_BASE.child("data").child("bars")
var REF_BASE: FIRDatabaseReference {
return REF_BASE
}
var REF_BARS: FIRDatabaseReference {
return _REF_BARS
}
}
And my modified viewController file (i did not use a tableViewController)
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
#IBOutlet weak var myTableView: UITableView!
var baruri = [Bar]()
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
DataService.ds.REF_BARS.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print(snap)
if let barData = snap.value as? Dictionary<String, AnyObject> {
let bar = Bar(barData: barData)
self.baruri.append(bar)
print(self.baruri)
self.myTableView.reloadData()
}
self.myTableView.reloadData()
}
self.myTableView.reloadData()
}
self.myTableView.reloadData()
}
)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return baruri.count
}
func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.myTableView.dequeueReusableCell(withIdentifier: "newCell", for: indexPath) as! NewCell
var baruriTabel: Bar!
baruriTabel = baruri[indexPath.row]
cell.barNameLBl.text = baruriTabel.name
cell.followersNrLbl.text = String(baruriTabel.followers)
cell.areaLbl.text = baruriTabel.area
cell.addedToFavoritesLbl.text = String(baruriTabel.addedToFav)
cell.happyHourLbl.text = baruriTabel.happyHour
cell.urlLbl.text = baruriTabel.url
cell.lattitudeLbl.text = String(baruriTabel.latitude)
cell.longitudeLbl.text = String(baruriTabel.longitude)
cell.phoneLbl.text = String(baruriTabel.phone)
cell.zipCode.text = String(baruriTabel.zipCode)
return cell
}
}
I am currently trying to load data from Parse (which I realize will soon be obselete but I have to stay on it for now) and I have a custom class that is to handle all the data from the backend like so:
import Foundation
import Parse
class FeedContent: PFObject {
#NSManaged var address: String
#NSManaged var content: PFFile
#NSManaged var isVideo: Int
#NSManaged var attendeeObjectId: String
#NSManaged var created: NSDate?
#NSManaged var objId: String
init(address: String, content: PFFile, isVideo: Int, attendeeObjectId: String, created: NSDate?, objId: String) {
super.init()
self.address = address
self.content = content
self.isVideo = isVideo
self.attendeeObjectId = attendeeObjectId
self.created = createdAt
self.objId = objId
}
override init() {
super.init()
}
}
extension FeedContent: PFSubclassing {
class func parseClassName() -> String {
return "FeedContent"
}
override class func initialize() {
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
}
and in my Display View Controller I am creating an array to house these items then calling a function to display the data , like here:
func addPFObjectInFeedContent(object : PFObject) {
let newItem = FeedContent()
newItem.address = (object["address"] as? String)!
newItem.isVideo = (object["isVideo"] as? Int)!
newItem.attendeeObjectId = (object["attendeeObjectId"] as? String)!
//newItem.eventObjectId = (object["eventObjectId"] as? String)!
newItem.content = (object["content"] as? PFFile)!
newItem.created = object.createdAt
newItem.objId = object.objectId!
self.feedContentItems.append(newItem)
}
Here is the array as well:
var feedContentItems = [FeedContent]()
On this line specifically is where the EXC_Breakpoint error occurs:
newItem.isVideo = (object["isVideo"] as? Int)!
so i was curious if anyone had any intimation of what may be happening?
func loadParseFeed() {
let contentQuery = PFQuery(className: "FeedContent")
contentQuery.whereKey("address", equalTo: defaults.objectForKey("newLocation")! as! String)
//contentQuery.whereKey("flagged", notEqualTo: true)
contentQuery.orderByDescending("createdAt")
if blacklist.count != 0 {
for var item = 0; item <= blacklist.count; item += 1 {
contentQuery.whereKey("attendeeObjectId", equalTo: blacklist[item])
}
}
contentQuery.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?,error: NSError?) -> Void in
if error == nil {
if let object = objects as [PFObject]? {
if objects!.count > 0 {
for thing in objects! {
// let newItem = FeedContent()
// newItem.isVideo = (thing["isVideo"] as? Int)!
// newItem.attendeeObjectId = (thing["attendeeObjectId"] as? String)!
// newItem.eventObjectId = (thing["eventObjectId"] as? String)!
// newItem.content = (thing["content"] as? PFFile)!
// newItem.created = thing.createdAt
// newItem.objId = thing.objectId!
// self.feedContentItems.append(newItem)
self.addPFObjectInFeedContent(thing)
}
self.advanceFeed()
// self.overviewTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "advanceFeed", userInfo: nil, repeats: true)
// self.overviewTimer.fire()
}
}
}
})
}