converting AnyObject to Array list of Strings in swift - swift

I'm new to swift and i'm extracting data from Parse database.
The data column is stored as array in the database
i managed to extract it as AnyObject and now i want to display each item. AnyObject is displaying as 1 entry instead of array list
class PeopleTable: UITableViewController {
//let textCellIdentifier = "TextCell"
//var window: UIWindow?
//let emptyArray: [AnyObject] = []
var userFriends: [AnyObject] = []
override func viewDidLoad() {
super.viewDidLoad()
queryForTable()
print(userFriends)
}
func queryForTable() {
let relationQuery = PFQuery(className:"User_info")
relationQuery.whereKey("userID", equalTo:"id123")
var userfrnds = try? relationQuery.findObjects()
for eachFriend in userfrnds! {
self.userFriends.append(eachFriend["friends"])
}
}
print(userFriends) command Out Put :
[(
Rudzani,
Terrence,
Thendelano,
"Big-T",
Smallboy
)]
i want the out put to be :
Rudzani,
Terrence,
Thendelano,
"Big-T",
Smallboy
How do i convert AnyObject to Array list of Strings

userFriends is an array in an array, the printed output is of type [[String]].
var userFriends = []
Then get the inner array
let users = userFriends[0]
and join the items
let users = userFriends[0].joinWithSeparator(", ")
As the type is distinct, any further type casting is not needed.
Edit: You have probably to cast the type after retrieving the object
do {
let userfrnds = try relationQuery.findObjects()
for eachFriend in userfrnds {
self.userFriends.append(eachFriend["friends"] as! [String])
}
} catch let error as NSError {
print(error)
}

Related

fetched json data Dictionary or array is empty in viewdidload or tableview datasource?

I want to add strings from an array of dictionary from backend.
but it's always empty outside the fetch function
//fetch data
func fetchFaqs(){
let manager = APIManager()
manager.parsingGet(url: BaseURL.faqs) { (JSON, Status) in
if Status {
let dict = JSON.dictionaryObject
let data = dict!["data"] as! [[String:Any]]
self.faqs = data as! [[String : String]]
}
}
}
//Viewdidload
class FaqViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var faqs = [[String:String]]()
var questions = NSMutableArray()
var answers = NSMutableArray()
#IBOutlet var faqsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fetchFaqs()
self.faqsTableView.reloadData()
print(faqs)
// faqsTableView.rowHeight = UITableView.automaticDimension
// faqsTableView.estimatedRowHeight = 600
}
}
Reload the tableview inside the api call closure in Main thread
func fetchFaqs(){
let manager = APIManager()
manager.parsingGet(url: BaseURL.faqs) { (JSON, Status) in
if Status {
let dict = JSON.dictionaryObject
let data = dict!["data"] as! [[String:Any]]
self.faqs = data as! [[String : String]]
DispatchQueue.main.async {
self.faqsTableView.reloadData()
}
}
}
}

Using UISearchbar with JSON to filter the result

I am fetching the data from JSON using http in the following code:
I have an ObjectModel, DownloadModelProtocol, and TableViewController
(Modal.swift)
class OrderItemModal: NSObject {
var deptname: String!
var staffname: String!
var status: String!
var userid: String!
}
(DownloadOrderModal.swift):
protocol OrderDownloadProtocol: class {
func itemsDownload(items: Array<Any>)
}
...
let bmsOrders = NSMutableArray()
...
weak var delegate: OrderDownloadProtocol!
let urlPath = "http://localhost/production/api/db_orders.php"
func downloadItems() {
let url = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
...
for i in 0..<jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let bmsOrder = OrderItemModal()
....
bmsOrders.add(bmsOrder)
....
declaration:
var orderItems = [OrderItemModal]()
var filterArray= [OrderItemModal]()
func itemsDownload(items: Array<Any>) {
orderItems = items as! [OrderItemModal]
}
and viewDidLoad:
let bmsOrder = DownloadOrderModal()
bmsOrder.delegate = self
bmsOrder.downloadItems()
this is the JSON result:
(
{
"deptname" = "Production";
"staffname" = Warehouse;
"status" = 1;
"userid" = ware;
})
This the the search bar code
filterArray = orderItems.filter( { ($0. staffname) (of: searchText, options: .caseInsensitive) })
And finally, this is the error:
Cannot assign value of type '[OrderItemModal]' to type '[String]'
Ultimately, I will populate the data into a table.
You have a few issues. It seems that orderItems is an NSArray array of OrderItemModal values. The first thing you need to do is to stop using NSArray and use a Swift array of the proper type. In this case it should be [OrderItemModal]. You will need to ensure filterArray is also declared as [OrderItemModal].
The result of a filter on such an array will be an array of OrderItemModal but you are attempting to force cast the result as an array of String.
You are also force-casting the closure to be (Any) -> Bool. There's no need for that.
And lastly, you are needlessly using NSString. Stick with String.
All you need is:
filterArray = orderItems.filter { (item) -> Bool in
return item.staffname.range(of: searchText, options: .caseInsensitive) != nil
}
Even simpler:
filterArray = orderItems.filter { $0.staffname.range(of: searchText, options: .caseInsensitive) != nil }

Appending Two String Arrays in Tuple

I am trying to append two Sting Arrays in tuple but it gives me error?
This is my class:
import UIKit
var tuple : [(String, String)] = []
class ViewController: UIViewController , UICollectionViewDelegate{
let reuseIdentifier = "cell"
var url : [String] = []
var image : [String] = []
override func viewDidLoad(){
}
override func viewWillAppear(animated: Bool) {
for i in tuple{
url.append(i.0)
image.append(i.1)
print("URL values.............. \(url)")
print("Image values.............. \(image)")
}
NSUserDefaults.standardUserDefaults().setObject(url, forKey: "u")
NSUserDefaults.standardUserDefaults().setObject(image, forKey: "i")
NSUserDefaults.standardUserDefaults().synchronize()
var u = NSUserDefaults.standardUserDefaults().objectForKey("u")
var i = NSUserDefaults.standardUserDefaults().objectForKey("i")
tuple.removeAll()
tuple.append(u,i)
}
When I change the types to this:
var u : String = NSUserDefaults.standardUserDefaults().objectForKey("u") as! String
var i : String = NSUserDefaults.standardUserDefaults().objectForKey("i") as! String
Now it gives me that error:
How can I append a tuple to an array?
[Code removed]
Also, as a user told you in comment, naming an array tuple is bad habit. The name tuples would fit already much better
EDIT: As #originaluser2 said, you can also use tuple.append((u,i))
EDIT2: I think this is definitely what you're looking for (I also adjusted names to avoid confusion, you should too)
import UIKit
class ViewController: UIViewController , UICollectionViewDelegate{
let reuseIdentifier = "cell"
var tuples: [(String, String)] = []
var urls: [String] = []
var images: [String] = []
override func viewDidLoad(){
}
override func viewWillAppear(animated: Bool) {
for i in tuples {
urls.append(i.0)
images.append(i.1)
print("URL values.............. \(urls)")
print("Image values.............. \(images)")
}
NSUserDefaults.standardUserDefaults().setObject(urls, forKey: "u")
NSUserDefaults.standardUserDefaults().setObject(images, forKey: "i")
NSUserDefaults.standardUserDefaults().synchronize()
// Cast objects as NSArray, since it's a subclass of NSObject
// Only NSObject derivate classes can be used for these purposes
let u = NSUserDefaults.standardUserDefaults().objectForKey("u") as! NSArray
let i = NSUserDefaults.standardUserDefaults().objectForKey("i") as! NSArray
tuples.removeAll()
// For every element of the first NSArray
for index in 0 ..< u.count {
// Append in the tuples array the strings at position index
// of both array
// NSString and String class are bridged, so you can use them both
// in order to accomplish your needs. An NSArray btw can store NSString, but not String objects
tuples.append((u.objectAtIndex(index) as! String,i.objectAtIndex(index) as! String))
}
}
}

Cannot convert value of type 'String?!' to expected argument type 'Notifications'

I am trying to check the id of a record before I put it into the array, using xcode swift
here is the code. But, i get the following error
Notifications.swift:50:46: Cannot convert value of type 'String?!' to expected argument type 'Notifications'
on this line
*if (readRecordCoreData(result["MessageID"])==false)*
Please can some one help to explain this error
import CoreData
struct Notifications{
var NotifyID = [NSManagedObject]()
let MessageDesc: String
let Messageid: String
init(MessageDesc: String, Messageid:String) {
self.MessageDesc = MessageDesc
self.Messageid = Messageid
// self.MessageDate = MessageDate
}
static func MessagesWithJSON(results: NSArray) -> [Notifications] {
// Create an empty array of Albums to append to from this list
var Notification = [Notifications]()
// Store the results in our table data array
if results.count>0 {
for result in results {
//get fields from json
let Messageid = result["MessageID"] as! String
let MessageDesc = result["MessageDesc"] as? String
let newMessages = Notifications(MessageDesc: MessageDesc!, Messageid:Messageid)
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
}
}
return Notification
}
//check id
func readRecordCoreData(Jsonid: String) -> Bool {
var idStaus = false
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ItemLog")
//3
do {
let resultsCD = try! managedContext.executeFetchRequest(fetchRequest)
if (resultsCD.count > 0) {
for i in 0 ..< resultsCD.count {
let match = resultsCD[i] as! NSManagedObject
let id = match.valueForKey("notificationID") as! String
if (Jsonid as String! == id)
{
idStaus = true
}
else{
idStaus = false
}
}
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
return idStaus
}
One of your methods is static and the other one is not :
func readRecordCoreData(Jsonid: String) -> Bool
static func MessagesWithJSON(results: NSArray) -> [Notifications]
Depending on what you want to accomplish you could declare both static, none, or replace
//check with id's from core data
if (readRecordCoreData(result["MessageID"])==false)
{
Notification.append(newMessages)
}
By
//check with id's from core data
if (Notifications.readRecordCoreData(Messageid)==false)
{
Notification.append(newMessages)
}
Not sure if the code will work past compilation however as there are many readability issues

Append Firebase Data into [String]() in Swift

I have data like below
I want to get the value of all objectIds and append it to a [String]() in Swift. Though when I use the append function, it first adds one, then two, and then three and so on. Below is the code I'm using right now.
var ObjectID: [String]?
override func viewDidLoad() {
super.viewDidLoad()
self.ObjectID = [];
let ref = Firebase(url:"https://blazing-heat-3676.firebaseio.com/results")
ref.queryOrderedByChild("objectId").queryLimitedToLast(201).observeEventType(.ChildAdded) { (snap: FDataSnapshot!) -> Void in
let objectId = snap.value["objectId"] as! String
self.ObjectID?.append(objectId)
print(self.ObjectID)
}
}
What modifications should I make for all objectIds to be in the array.
Firebase have no arrays but if the data looks like an array, Firebase clients will render it as an array. Therefore you can simply convert the result into an array and work with each individual object of this array.
let firebase = Firebase(url: "https://blazing-heat-3676.firebaseio.com/results")
firebase.observeSingleEventOfType(.Value) { (snapshot: FDataSnapshot!) -> Void in
guard let jsonArray: [JSON] = snapshot.value as? [JSON] else {
return
}
var objectIds: [String] = []
for json in jsonArray {
if let id = json["objectId"] as? String {
objectIds.append(id)
}
}
// Print result
print(objectIds)
}
Where JSON is
public typealias JSON = [String : AnyObject]
As an alternative solution - you can model this into query but you get the idea.
var myString: String = ""
ref.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let name = child.value.objectForKey("ObjectId") as! String
myString += name
}
print(myString)
})
Also, you may want to re-think your keys (node names) as numeric sequential indexes are hard to work with. You should check into childByAutoId.
Also, Firebase does support arrays via NSArray however, there are usually much better alternatives.