getting 0 values inside my array from getdocument which insdie getdocuments - ios

iam working with firestore i have two structs
one called history
aother called cart
simply hisory struct is
struct UserOrderHistoryModel {
var id : String? = ""
var dateOrderCreated : String? = ""
var cartArray : [CartItemModel]
}
struct CartItemModel {
var id : String? = ""
var restaurantImageUrl : String
var restaurantTitle : String
var menuItemImageUrl : String
var menuItemTitle : String
var countOfMenuItemSelected : Int
}
what i am trying to do is load history so i use getdocument to get the id and the date
i wanted to get order collection which inside history document
so i use another getdocuments inside the first one
func loadUserOrderHistory(completion : #escaping (_ error :Error? ,_ userHistoryArray : [UserOrderHistoryModel]?) -> ()) {
var historyArray = [UserOrderHistoryModel]()
let userHistoryRef = USERS.document(UserConfigurations.currentUserID!).collection("history")
userHistoryRef.getDocuments { (snapShots, error) in
if error != nil {
completion(error , nil)
}else {
historyArray.removeAll()
for document in snapShots!.documents {
let historyId = document.documentID
let historyData = document.data()
let historyDate = historyData["date_order_created"] as? Timestamp ?? nil
let historyDateToString = String(describing: historyDate?.dateValue())
var orderArray = [CartItemModel]()
self.loadUserHistoryOrders(histroyDocumentReference: userHistoryRef.document(historyId), completion: { (error, cartArray) in
if error != nil {
print(error!)
}else {
orderArray = cartArray!
}
})
let userHistory = UserOrderHistoryModel(id: historyId, dateOrderCreated: historyDateToString , cartArray: self.orderArray)
historyArray.append(userHistory)
}
completion(nil , historyArray)
}
}
}
private func loadUserHistoryOrders( histroyDocumentReference : DocumentReference, completion : #escaping (_ error : Error? ,_ historyOrders : [CartItemModel]? ) -> ()) {
var cartArray = [CartItemModel]()
histroyDocumentReference.collection("orders").getDocuments { (snapShot, error) in
if error != nil {
completion(error,nil)
}else {
for document in snapShot!.documents {
let id = document.documentID
let cartDictionary = document.data()
let restaurantImageUrl = cartDictionary["restaurant_imageurl"] as? String ?? "none"
let restaurantName = cartDictionary["restaurant_title"] as? String ?? "none"
let menuItemImageUrl = cartDictionary["menuItem_imageurl"] as? String ?? "none"
let menuItemName = cartDictionary["menuItem_title"] as? String ?? "none"
let count = cartDictionary["number_of_selected_menuitem"] as? Int ?? 0
let cart = CartItemModel(id: id, restaurantImageUrl: restaurantImageUrl, restaurantTitle: restaurantName, menuItemImageUrl: menuItemImageUrl, menuItemTitle: menuItemName, countOfMenuItemSelected: count)
cartArray.append(cart)
}
completion(nil , cartArray)
}
}
}
so orderArray inside second getdocumnet which i put it inside another function called loadUserHistoryOrders
i debugged the code and found that
once i get to end of the this function orderArray is back to 0 values
here is the pics of my firestore
url of pics : https://drive.google.com/open?id=1NX8NIUN2Yb9m3_7A8EnZgAxWe8xuhNDh
Update :
i solved the problem by adding completion of loadUserOrderHistory inside the call of the second method loadUserHistoryOrders
func loadUserOrderHistory(completion : #escaping (_ error :Error? ,_ userHistoryArray : [UserOrderHistoryModel]?) -> ()) {
var historyArray = [UserOrderHistoryModel]()
let userHistoryRef = USERS.document(UserConfigurations.currentUserID!).collection("history")
userHistoryRef.getDocuments { (snapShots, error) in
if error != nil {
completion(error , nil)
}else {
historyArray.removeAll()
for document in snapShots!.documents {
let historyId = document.documentID
let historyData = document.data()
let historyDate = historyData["date_order_created"] as? Timestamp ?? nil
let historyDateToString = String(describing: historyDate?.dateValue())
var orderArray = [CartItemModel]()
self.loadUserHistoryOrders(histroyDocumentReference: userHistoryRef.document(historyId), completion: { (error, cartArray) in
if error != nil {
print(error!)
}else {
orderArray = cartArray!
let userHistory = UserOrderHistoryModel(id: historyId, dateOrderCreated: historyDateToString , cartArray: self.orderArray)
historyArray.append(userHistory)
completion(nil , historyArray)
}
})
}
}
}
}

Related

Unexpectedly found nil while unwrapping... MessageKit

I have a struct set up for Messages and each time I got to load messages in app, I receive an unexpectedly found nil error on this line of code -->
var chatPartnerId: String {
return isFromCurrentUser ? toID! : fromID! // where I get the error
}
I can't figure out what Im doing wrong here at all.
Here's the class setup:
struct Message: MessageType {
let id: String?
var messageId: String {
return id ?? UUID().uuidString
}
var content: String?
var toID: String?
var fromID: String?
var isFromCurrentUser = Bool()
var chatPartnerId: String {
return isFromCurrentUser ? toID! : fromID!
}
let sentDate: Date
let sender: SenderType
var image: UIImage?
var downloadURL: URL?
var kind: MessageKind {
if let image = image {
let mediaItem = ImageMediaItem(image: image)
return .photo(mediaItem)
} else {
return .text(content ?? "")
}
}
init(user: User, content: String, fromID: String, toID: String) {
sender = Sender(senderId: user.uid!, displayName: user.name!)
self.content = content
self.fromID = fromID
self.toID = toID
sentDate = Date()
id = nil
}
init(user: User, image: UIImage) {
sender = Sender(senderId: user.uid!, displayName: user.name!)
self.image = image
content = ""
fromID = ""
toID = ""
sentDate = Date()
id = nil
}
init?(document: QueryDocumentSnapshot) {
let data = document.data()
guard
let sentDate = data["created"] as? Timestamp,
let senderId = data["senderId"] as? String,
let fromID = data["fromID"] as? String,
let toID = data["toID"] as? String,
let senderName = data["senderName"] as? String
else {
return nil
}
id = document.documentID
self.sentDate = sentDate.dateValue()
sender = Sender(senderId: senderId, displayName: senderName)
self.isFromCurrentUser = fromID == Auth.auth().currentUser?.uid
if let content = data["content"] as? String {
self.content = content
downloadURL = nil
} else if let urlString = data["url"] as? String, let url = URL(string: urlString) {
downloadURL = url
content = ""
} else {
return nil
}
}
}
// MARK: - DatabaseRepresentation
extension Message: DatabaseRepresentation {
var representation: [String: Any] {
var rep: [String: Any] = [
"created": sentDate,
"senderId": sender.senderId,
"fromID": fromID,
"toID": toID,
"senderName": sender.displayName
]
if let url = downloadURL {
rep["url"] = url.absoluteString
} else {
rep["content"] = content
}
return rep
}
}
// MARK: - Comparable
extension Message: Comparable {
static func == (lhs: Message, rhs: Message) -> Bool {
return lhs.id == rhs.id
}
static func < (lhs: Message, rhs: Message) -> Bool {
return lhs.sentDate < rhs.sentDate
}
}
Both toID and fromID are optionals and may be nil. Avoid force unwrapping the optional (and actually avoid force unwrapping anything else, with very rare exceptions), like you do in the problematic statement.
Instead, you can:
Don't be afraid to return an optional:
var chatPartnerId: String? { // <-- returns optional
return isFromCurrentUser ? toID : fromID
}
In many cases it's much better to deal with the nil as a condition that helps you understand the state of the app. For example nil may mean you should skip the processing of such message.
You can return a default bogus ID, or an empty string:
var chatPartnerId: String {
guard let id = isFromCurrentUser ? toID : fromID else {
return "" // <-- returns bogus ID
}
return id
}
You can change the property to be required:
var toID: String // <-- not optional
var fromID: String // <-- not optional
Looking at all of your inits I see none of them allows these paramters to be nil. So you don't need to make them optional.

DatabaseReference.observe is not called in swift4

I am trying to fetch the data from firebase. I am calling a function which has a databaseReference but it is not calling up.Basically this function is also called from databaseRefernce only of another function.
Here is my code:
func prepareCoursesFromCourseNodewithAllCoursesList(allCourseList: [Any]){
var courseDetailsNode = String()
var courseCount = allCourseList.count
weak var weakSelf = self
var courseId = String()
var localCoursesAndCardDictionary = [AnyHashable: Any]()
for singleCourse in allCourseList as! [[String:Any]] {
if singleCourse["elementId"] != nil {
courseId = "\(String(describing: singleCourse["elementId"]!))"
}else{
if singleCourse["currentCourseId"] != nil {
courseId = "\(String(describing: singleCourse["currentCourseId"]!))"
}
}
if singleCourse["parentNodeName"] != nil {
if singleCourse["parentNodeName"] as! String == "course" {
//this is course
courseDetailsNode = IMERCOURSE_URL
}
else {
//this is course Collection
courseDetailsNode = IMERCOURSECOLLECTION_URL
}
}
var reference = DatabaseReference()
let courseURL = "\(FIREBASE_URL)\(courseDetailsNode.replacingOccurrences(of: "{Id}", with: courseId))"
reference = Database.database().reference(fromURL: courseURL)
self.addIntoListFirebaseRef(firebaseRef: ref)
reference.observe(DataEventType.value, with: { (snapShot:DataSnapshot) in
courseCount -= 1
if snapShot.value != nil {
let singleCourseDictionary = snapShot.value as? [String: Any]
localCoursesAndCardDictionary[courseId] = singleCourseDictionary
self.settingUserDetailsViewData()
(Constants.sharedTools() as AnyObject).hideProgressIndicator()
}
}
}, withCancel: { (error:Error) in
})
}
}
}
this prepareCoursesFromCourseNodewithAllCoursesList(allCourseList: [Any]) is called from another databaseRefernce.ObserveEevnt
value.

How to remove the dictionary in an array which id was equal to the value comparing in swift 3?

Here I am having two values which is 46 and 47 in customFlashId and customLikeId here i am getting dynamically and I need to compare the values in categories model class children data array and I just need to remove which id matches with new comparing value that needs to be removed from model class and need to update it according to new results can anyone help me how to resolve this ?
I tried this
self.categoriesModel?.childrenData = (self.categoriesModel?.childrenData.filter({$0.id == self.customLikeId || $0.id == self.customFlashId}))!
and another one I tried is this
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
self.categoriesModel = Categories(json: jsonObj as [String : AnyObject])
DispatchQueue.main.async {
for item in 0...(self.categoriesModel?.childrenData.count)! - 1 {
if self.categoriesModel?.childrenData[item].childrenData != nil || self.categoriesModel?.childrenData[item].childrenData.count != 0 {
if self.categoriesModel?.childrenData[item].id == Int(self.customFlashId!) || self.categoriesModel?.childrenData[item].id == Int(self.customLikeId!) {
}
else {
if self.categoriesModel?.childrenData[item].includeInMenu == true {
self.categoriesModel?.childrenData.append((self.categoriesModel?.childrenData[item])!)
}
}
}
}
Here is my model class data
struct Categories {
let id : Int?
let parentId : Int?
let name : String?
let isActive : Bool?
let position : Int?
let level : Int?
let includeInMenu : Bool?
let parentLevelname : String?
let urlKey : String?
let brand : Any?
let image : String?
let productCount : Int?
var childrenData = [Categories]()
init?(json : [String:Any]) {
self.id = json["id"] as? Int ?? 0
self.parentId = json["parent_id"] as? Int ?? 0
self.name = json["name"] as? String ?? ""
self.isActive = json["status"] as? Bool ?? false
self.position = json["position"] as? Int ?? 0
self.level = json["level"] as? Int ?? 0
self.includeInMenu = json["include_in_menu"] as? Bool ?? false
self.parentLevelname = json["parent_level_name"] as? String ?? ""
self.urlKey = json["url_key"] as? String ?? ""
self.brand = json["brand"]
self.image = json["image"] as? String ?? ""
self.productCount = json["product_count"] as? Int ?? 0
if let customAttribute = json["children_data"] as? [[String: AnyObject]] {
var result = [Categories]()
for obj in customAttribute {
result.append(Categories(json: obj )!)
}
self.childrenData = result
} else {
self.childrenData = [Categories]()
}
}
}
and my category url follows as http://www.json-generator.com/api/json/get/cflnNlfhxK?indent=2

Remove duplicate elements in swift array of objects

So I have a section in my app which displays events that your followers are going to. I successfully pull the followers and there corresponding events. I then add those events to a bigger array of event objects. I am currently having trouble removing the duplicates I have tried many extensions but it doesn't seem to be working. I figure it is because the array contains different objects with different memory addresses so when I compare them they aren't the same regardless of the fact that the content is. I have been messing with this for a while now and can't really figure anything out. if anyone could help me I would appreciate it.
This is the method grabs the events and returns them to an array in my main VC.
static func showFollowingEvent(for followerKey: String,completion: #escaping (Event) -> Void) {
//getting firebase root directory
let ref = Database.database().reference()
ref.child("users").child(followerKey).child("Attending").observeSingleEvent(of: .value, with: { (attendingSnapshot) in
print(attendingSnapshot)
guard var eventKeys = attendingSnapshot.children.allObjects as? [DataSnapshot] else{return}
for event in eventKeys{
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
EventService.show(forEventKey: event.key, completion: { (event) in
dispatchGroup.leave()
completion(event!)
})
}
}) { (err) in
print("couldn't grab event info",err)
}
} print("couldn't grab event info",err)
}
}
This is the function that receives the events and reloads the collectionView upon getting them.
#objc func grabFriendsEvents(){
print("Attempting to see where your friends are going")
UserService.following { (user) in
for following in user {
print(following.username as Any)
PostService.showFollowingEvent(for: following.uid, completion: { (event) in
self.friendsEvents.append(event)
// self.friendsEvents.append(contentsOf: event)
// leave here
self.allEvents2["Friends Events"] = self.friendsEvents.removeDuplicates()
self.collectionView?.reloadData()
})
}
}
}
I tried these extensions which I saw in previous questions and nothing worked.
extension Array where Element: Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
mutating func removeDuplicatesTwo() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
}
import Foundation
import FirebaseDatabase.FIRDataSnapshot
#objc(Event)
class Event:NSObject{
var key: String?
let currentEventName: String
let currentEventImage: String
let currentEventPromo: String?
let currentEventDescription: String
//nested properties
let currentEventStreetAddress: String
let currentEventCity: String
let currentEventState: String
let currentEventDate: String?
let currentEventEndDate: String?
let currentEventTime: String?
let currentEventEndTime: String?
let currentEventZip: Int
var category: String
//nested properties stop
var currentAttendCount: Int
var isAttending = false
var eventDictionary: [String: Any]{
let dateDict = ["start:date":currentEventDate, "start:time": currentEventTime,"end:time":currentEventEndTime, "end:date": currentEventEndDate]
return ["event:name":currentEventName,"event:imageURL" : currentEventImage,
"event:description": currentEventDescription, "attend:count": currentAttendCount,
"event:street:address": currentEventStreetAddress,"event:zip": currentEventZip,
"event:state": currentEventState, "event:city": currentEventCity, "event:promo": currentEventPromo ?? "", "event:date": dateDict, "event:category":category]
}
init(currentEventKey: String, dictionary: [String:Any]) {
self.key = currentEventKey
self.currentEventName = dictionary["event:name"] as? String ?? ""
self.currentEventImage = dictionary["event:imageURL"] as? String ?? ""
self.currentEventDescription = dictionary["event:description"] as? String ?? ""
self.currentEventPromo = dictionary["event:promo"] as? String ?? ""
self.currentAttendCount = dictionary["attend:count"] as? Int ?? 0
self.category = dictionary["event:category"] as? String ?? ""
//nested properties
self.currentEventStreetAddress = dictionary["event:street:address"] as? String ?? ""
self.currentEventCity = dictionary["event:city"] as? String ?? ""
self.currentEventState = dictionary["event:state"] as? String ?? ""
self.currentEventZip = dictionary["event:zip"] as? Int ?? 0
let eventDate = dictionary["event:date"] as? [String: Any]
self.currentEventDate = eventDate?["start:date"] as? String ?? ""
self.currentEventTime = eventDate?["start:time"] as? String ?? ""
self.currentEventEndTime = eventDate?["end:time"] as? String ?? ""
self.currentEventEndDate = eventDate?["end:date"] as? String ?? ""
}
init?(snapshot: DataSnapshot) {
guard let dict = snapshot.value as? [String : Any],
let currentEventName = dict["event:name"] as? String,
let currentEventImage = dict["event:imageURL"] as? String,
let currentEventDescription = dict["event:description"] as? String,
let currentEventPromo = dict["event:promo"] as? String,
let category = dict["event:category"] as? String,
let currentEventStreetAddress = dict["event:street:address"] as? String,
let currentEventCity = dict["event:city"] as? String,
let currentEventState = dict["event:state"] as? String,
let currentEventZip = dict["event:zip"] as? Int,
let currentAttendCount = dict["attend:count"] as? Int,
let eventDate = dict["event:date"] as? [String: Any],
let currentEventDate = eventDate["start:date"] as? String,
let currentEventEndDate = eventDate["end:date"] as? String,
let currentEventTime = eventDate["start:time"] as? String,
let currentEventEndTime = eventDate["end:time"] as? String
else { return nil }
self.key = snapshot.key
self.currentEventName = currentEventName
self.currentEventImage = currentEventImage
self.currentEventDescription = currentEventDescription
self.currentEventStreetAddress = currentEventStreetAddress
self.currentEventCity = currentEventCity
self.currentEventState = currentEventState
self.currentEventZip = currentEventZip
self.currentAttendCount = currentAttendCount
self.currentEventPromo = currentEventPromo
self.currentEventDate = currentEventDate
self.currentEventTime = currentEventTime
self.currentEventEndTime = currentEventEndTime
self.category = category
self.currentEventEndDate = currentEventEndDate
}
static func ==(lhs: Event, rhs: Event) -> Bool {
return lhs.key == rhs.key
}
}
Classes of type NSObject will automatically call isEqual() for the contains() method. You can override the superclass's implementation to fit your logic.
If your class HAS to inherit NSObject, then use:
class Event: NSObject {
var key: String?
init(key: String) {
self.key = key
}
override func isEqual(_ object: Any?) -> Bool {
guard let event = object as? Event else { return false }
return self.key == event.key
}
}
var event = Event(key: "abc")
var eventCopy = Event(key: "abc")
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
return reduce(into: []) { result, element in
if !result.contains(element) {
result.append(element)
}
}
}
}
var events = [event, eventCopy]
events = events.removeDuplicates()
print(events.count)
If your class does not inherit NSObject, make it conform to the Equatable protocol.
class Event: Equatable {
var key: String?
init(key: String) {
self.key = key
}
static func ==(lhs: Event, rhs: Event) -> Bool {
return lhs.key == rhs.key
}
}
var event = Event(key: "abc")
var eventCopy = Event(key: "abc")
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
var events = [event, eventCopy]
events = events.removeDuplicates()
print(events.count)
You have to make Event class conform to Equatable protocol

How to save and fetch data from file in swift?

I want to save the response from JSON in a file and fetch from it when the network is not available. However on trying to fetch idea by disabling the wifi, the app always crashes. Are there any other ways for offline fetching in swift except saving in database??
This is the error I am getting : Could not cast value of type 'Swift._NSContiguousString' (0x109e22320) to 'NSArray'
This is what I have done so far:
Create a model
class Directory : NSObject, NSCoding {
var data : [AnyObject]
var tid : String
var vid : String
var name : String
var imgThumbnail : String
var imgMedium : String
var imgLarge : String
var child : String
// MARK: Archiving Paths
init(data:[AnyObject],tid:String,vid:String,name:String,imgThumbnail:String,imgMedium:String,imgLarge:String,child:String) {
self.data = data ?? []
self.tid = tid ?? ""
self.vid = vid ?? ""
self.name = name ?? ""
self.imgThumbnail = imgThumbnail ?? ""
self.imgMedium = imgMedium ?? ""
self.imgLarge = imgLarge ?? ""
self.child = child ?? ""
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(data, forKey:Constants.kData)
aCoder.encodeObject(name, forKey:Constants.Directory.kName )
aCoder.encodeObject(tid, forKey: Constants.Directory.tid)
aCoder.encodeObject(vid, forKey: Constants.Directory.vid)
aCoder.encodeObject(imgThumbnail, forKey:Constants.Directory.kImageThumbnail)
aCoder.encodeObject(imgMedium, forKey: Constants.Directory.kImageMedium)
aCoder.encodeObject(imgLarge, forKey: Constants.Directory.kImageLarge)
aCoder.encodeObject(child, forKey: Constants.Directory.kChild)
}
required convenience init?(coder aDecoder: NSCoder) {
let data = aDecoder.decodeObjectForKey(Constants.kData) as! [AnyObject]
let name = aDecoder.decodeObjectForKey(Constants.Directory.kName) as! String
let tid = aDecoder.decodeObjectForKey(Constants.Directory.tid) as! String
let vid = aDecoder.decodeObjectForKey(Constants.Directory.vid) as! String
let imgThumbnail = aDecoder.decodeObjectForKey(Constants.Directory.kImageThumbnail) as! String
let imgMedium = aDecoder.decodeObjectForKey(Constants.Directory.kImageMedium) as! String
let imgLarge = aDecoder.decodeObjectForKey(Constants.Directory.kImageLarge) as! String
let child = aDecoder.decodeObjectForKey(Constants.Directory.kChild) as! String
// Must call designated initializer.
self.init(data:data,tid:tid,vid:vid,name:name,imgThumbnail:imgThumbnail,imgMedium: imgMedium,imgLarge: imgLarge, child: child)
}
}
Code for saving and loading the data from file
class func loadSavedFile(fileName: String) -> AnyObject? {
let pathString: String = Utility.fetchFilePathString(fileName)
print("Here the pathString is \(pathString)")
if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
return NSKeyedUnarchiver.unarchiveObjectWithFile(pathString)!
} else {
return "File doesn't exist"
}
return ""
}
class func saveObject(object: AnyObject, toFile fileName: String) {
let pathString: String = Utility.fetchFilePathString(fileName)
NSKeyedArchiver.archiveRootObject(object, toFile: pathString)
}
class func fetchFilePathString(fileName: String) -> String {
let pathAray: [AnyObject] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.AllDomainsMask, true)
let pathString = pathAray.last!
return NSURL(fileURLWithPath: pathString as! String).URLByAppendingPathComponent(fileName).absoluteString
}
Checking for network connection in the view controller
var directoryArr = [Directory]()
override func viewDidLoad() {
super.viewDidLoad()
if Utility.isNetworkReachable() {
Utility.saveObject([], toFile: Constants.File.kDirectory)
self.serviceCallDirectory()
} else {
self.directorie = (Utility.loadSavedFile(Constants.File.kDirectory) as? [Directory])!
self.tableView.reloadData()
}
Service Call
func serviceCallDirectory() -> Void {
let stringUrl = Constants.baseUrl + Constants.kDirectoryUrl
WebService.getRequestAPI(stringUrl, withSuccess: {(responseDic, Statusflag,error) in
if Statusflag {
self.tableView.backgroundColor = UIColor.clearColor()
self.tableView.hidden = false
let tempInfo = responseDic![Constants.kData] as! [AnyObject]
var imgthumbnail : String = ""
var imgmedium : String = ""
var imglarge : String = ""
var name : String = ""
var child : String = ""
if tempInfo.count != 0 {
for info in tempInfo {
let tid = info[Constants.Directory.tid] as! String
let vid = info[Constants.Directory.vid] as! String
if let names = info[Constants.Directory.kName] as? String {
name = names
}
if let childs = info[Constants.Directory.kChild] as? String {
child = childs
}
if let imgthumb = info[Constants.Directory.kImageThumbnail] as? String {
imgthumbnail = imgthumb
} else {
imgthumbnail = ""
}
if let imgmediumd = info[Constants.Directory.kImageMedium] as? String {
imgmedium = imgmediumd
} else {
imgmedium = ""
}
if let imglarges = info[Constants.Directory.kImageLarge] as? String {
imglarge = imglarges
}
let myModel = Directory(
data: tempInfo,
tid: tid,
vid: vid,
name: name,
imgThumbnail: imgthumbnail,
imgMedium: imgmedium,
imgLarge: "",
child: child
)
self.directorie.append(myModel)
}
I don't know that this is the only issue, but this code
class func loadSavedFile(fileName: String) -> AnyObject? {
let pathString: String = Utility.fetchFilePathString(fileName)
print("Here the pathString is \(pathString)")
if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
return NSKeyedUnarchiver.unarchiveObjectWithFile(pathString)!
} else {
return "File doesn't exist"
}
return ""
}
Either returns an object or a string. That's not very sensible. It should return a success flag or a tuple or use a completion block. When you call this function your code expects to get back an array of directory, which in a number of cases won't happen
self.directorie = (Utility.loadSavedFile(Constants.File.kDirectory) as? [Directory])!
The error in your question indicates a different kind of data mismatch. You should try not to use AnyObject, let swift help you by type checking what you're doing...

Resources