How to convert datas in Swift from NSArray to Dictionary? - swift

I need convert NSArray to Dictionary, but don't know how can I do it.
After fetch request I have result in NSArray. This my request:
var results: NSArray = []
func fetchUpdateAttendee() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Attendee")
let predicate = NSPredicate(format: "needUpdate != false")
fetchRequest.predicate = predicate
results = try! DBWorker.context.fetch(fetchRequest) as NSArray
results.forEach { result in
print(result)
}
var results: NSArray = []
print(results) give me
<Attendee: 0x60c000097750> (entity: Attendee; id: 0x60c000422200 <x-coredata:///Attendee/t9E88E2EE-9258-4FAE-AF80-9B036838C6D631> ; data: {
address = "1411 E 31st St";
affiliation = "";
attendeeType = nil;
city = Aguanga;
degree = MD;
email = "";
fax = "";
firstName = Oliver1212;
fullStateLicense = "";
id = nil;
lastName = Aalami;
meeting = nil;
needUpdate = 1;
phone = "";
signature = nil;
signatureTimeStamp = nil;
specialty = Surgery;
state = CA;
stateLicense = "";
status = nil;
timeStamp = nil;
zip = 92536;
})
I need to put these datas to: let dic4Attendee: [String: Any] = [:]

This is a Core Data NSManagedObject subclass, so the code is supposed to be
var results = [Attendee]()
func fetchUpdateAttendee() {
let fetchRequest = NSFetchRequest<Attendee>(entityName: "Attendee")
let predicate = NSPredicate(format: "needUpdate == TRUE")
fetchRequest.predicate = predicate
do {
results = try DBWorker.context.fetch(fetchRequest)
results.forEach { result in
print(result)
}
} catch { print(error) }
}
never use NSArray to represent an array of NSManagedObject subclass.
Add a property dictionaryRepresentation in the Attendee class and return the key value pairs you need for example
var dictionaryRepresentation : [String:Any] {
return ["address" : address,
"affiliation" : affiliation,
"city" : city
// and so on
]
}
then map the array
let mappedArray = results.map{ $0.dictionaryRepresentation }

Related

Parse Alamofire result swift

I'm very lost parsing the following response from an AF request – let json = result as! NSDictionary – in Swift:
{
errors = (
);
get = statistics;
parameters = {
country = germany;
};
response = (
{
cases = {
"1M_pop" = 14303;
active = 317167;
critical = 4179;
new = "+15161";
recovered = 863300;
total = 1200006;
};
continent = Europe;
country = Germany;
day = "2020-12-08";
deaths = {
"1M_pop" = 233;
new = "+380";
total = 19539;
};
population = 83900328;
tests = {
"1M_pop" = 347331;
total = 29141172;
};
time = "2020-12-08T09:15:08+00:00";
}
);
results = 1;
}
Any idea how to get the actual case numbers, i.e. for example the number of new cases?
So far I have tried the following (error throwing) approach:
if let responseDict = result as? NSDictionary {
if let data = responseDict.value(forKey: "response") as?
[NSDictionary] {
// Get case numbers
guard let cases = data[0]["cases"] else { return }
guard let casesPerOneMil = cases[0] as! Int else { return }
print(casesPerOneMil)
}
}
Basically don't use NS... collection types in Swift at all, use native types.
And don't use value(forKey, use key subscription.
And you have to conditional downcast Any to the expected concrete type.
There is another mistake: The object for cases is a dictionary, note the {} and you have to get the value for casesPerOneMil with key subscription, too
if let responseDict = result as? [String:Any],
let dataArray = responseDict["response"] as? [[String:Any]],
let firstDataItem = dataArray.first {
// Get case numbers
guard let cases = firstDataItem["cases"] as? [String:Any] else { return }
guard let casesPerOneMil = cases["1M_pop"] as? Int else { return }
print(casesPerOneMil)
}
}

SwiftUI - Include Relationship info in FetchRequest

I have an Expense entity with a one-to-many relationship to an Accounts Entity.
My current fetch request is as follows:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Expenses.entity().name ?? "Expenses")
request.predicate = predicate
request.returnsObjectsAsFaults = false
request.resultType = .dictionaryResultType
let expression = NSExpressionDescription()
// check operations list from apple or nshipster in nsexpressions
expression.expression = NSExpression(forFunction: "noindex:", arguments:[NSExpression(forKeyPath: "originAccounts.isCredit")])
expression.name = "checkIsCredit"
expression.expressionResultType = .booleanAttributeType // might be another
let expression1 = NSExpressionDescription()
expression1.expression = NSExpression(forFunction: "noindex:", arguments:[NSExpression(forKeyPath: "id")])
expression1.name = "checkExpenses"
expression.expressionResultType = .UUIDAttributeType
request.propertiesToFetch = [expression,expression1]
context.perform {
do {
let results = try request.execute()
print(results)
My Predicate is:
predicate: NSPredicate(format: "expenseDate >= %# AND expenseDate < %#", datesView.prevMonthPayStart as NSDate, datesView.nextPaydate as NSDate)
When I print the results I get
[{
expenseAccount = "Test Account";
expenseCategory = "Test Category";
expenseCost = 123;
expenseDate = "2020-11-12 05:00:00 +0000";
expenseIsPaid = 1;
expenseName = Test;
expenseType = "One-time";
id = "AFB5EB0E-20A2-47EA-8F36-22D07571C213";
shouldDupe = 1;
}, {
expenseAccount = "Test Account";
expenseCategory = "Test Category";
expenseCost = 23;
expenseDate = "2020-11-13 05:00:00 +0000";
expenseIsPaid = 0;
expenseName = "Test Recurring";
expenseType = Monthly;
id = "5CFB5E58-4377-40DA-9C6A-AF8027ACEC60";
shouldDupe = 1;
}]
I understand that I won't see attributes that are nil, but I want to get an attribute through originAccounts relationship. Is this possible? Specifically I want to get the value of originAccounts.isCredit. Here is an example object for reference.
<Expenses: 0x60000321af80> (entity: Expenses; id: 0xa7ab05bb9341bf4a <x-coredata://ED302202-3018-445F-8FFE-DD2E85219E64/Expenses/p1>; data: {
expenseAccount = "Test Account";
expenseCategory = "Test Category";
expenseCost = 123;
expenseDate = "2020-11-12 05:00:00 +0000";
expenseId = nil;
expenseIsPaid = 1;
expenseName = Test;
expenseType = "One-time";
id = "AFB5EB0E-20A2-47EA-8F36-22D07571C213";
lastMonthlyExpenseID = nil;
nextMonthlyExpenseID = nil;
originAccounts = "0xa7ab05bb9341bf4e <x-coredata://ED302202-3018-445F-8FFE-DD2E85219E64/Accounts/p1>";
originCategories = nil;
shouldDupe = 1;
})
Could you try NSExpressions, you won't make a fetch, therefore you'll be mutch efficient.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "yourEntity")
fetchRequest.predicate = NSPredicate(format: "yourPredicate")
fetchRequest.resultType = .dictionaryResultType
fetchRequest.returnsObjectsAsFaults = false
let expression = NSExpressionDescription()
// check operations list from apple or nshipster in nsexpressions
expression.expression = NSExpression(forFunction: "yourOperation", arguments:[NSExpression(forKeyPath: "Expenses.originAccounts.isCredit")])
expression.name = "yourName"
expression.expressionResultType = .decimalAttributeType // might be another
fetchRequest.propertiesToFetch = [expression]
do {
let results = try viewContext.fetch(fetchRequest)
print(results)
} catch {
print("Failed to fetch aggregates")
}
}

Predicate in realm with dictionary parameters

I want to create a predicate with a dictionary paramateres and filter data on realm, like
var parameters = [String: Any]()
parameters["Mobile"] = a.Mobile!
parameters["CategoryId"] = self.SelectCategryId
let existContact = (contactBiz.FetchMulti(parameters: parameters)?.count)! > 0
and in fetchMulti func I make a predicate and filter data
func FetchMulti(parameters: [String: Any])-> Results<RealmEntityType>?
{
do
{
let key = T.KeyName()
var object = realm.objects(RealmEntityType.self)
let subPredicates = parameters.map {
NSPredicate(format: "%# = %#", $0.key, $0.value as! CVarArg)
}
let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: subPredicates)
// var predictionArray = [String]()
// for p in parameters
// {
// predictionArray.append("\(p.key) = \(p.value) ")
//
// }
//
// let perdicate = predictionArray.joined(separator: " && ")
//
return object.filter(compoundPredicate);
}
catch
{
print(error.localizedDescription)
}
return nil
}
but I get this error
reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'
Any help!
You need to use %K to indicate that the value is the name of a key and not a constant string: NSPredicate(format: "%K = %#", $0.key, $0.value as! CVarArg)

Core Data Condition

I need to add a Core Data condition How do I do it? . If the record is in this condition, the "sonuc" variable will be true
Core data model:
If "kullaniciadi" is "emre" and "otogiris" is "1" then the "sonuc" will
be true
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if #available(iOS 10.0, *) {
return appDelegate.persistentContainer.viewContext
} else {
return DatabaseController.managedObjectContext
}
}
func otomatikGirisKontrol() -> Bool
{
var sonuc = false
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Kullanicilar")
fetchRequest.returnsObjectsAsFaults = false
do{
let results = try getContext().fetch(fetchRequest)
if results.count > 0
{
sonuc = true
}
else
{
sonuc = false
}
}
catch
{
}
return (sonuc)
}
Use a NSPredicate to fetch only Kullaniciar objects fitting your condition:
let fetchRequest = ...
let kullaniciadi = "emre"
let otogiris = "1"
let predicate = NSPredicate(format: "kullaniciadi = %# AND otogiris = %#", kullaniciadi, otogiris)
request.predicate = predicate
//... execute fetch request

iPhone get all albums/artists

does any of you have example code (or a link to it) of how to retrieve all music albums or artist from the iPod media library?
Thanks in advance!
Use a MPMediaQuery:
MPMediaQuery *allAlbumsQuery = [MPMediaQuery albumsQuery];
NSArray *allAlbumsArray = [allAlbumsQuery collections];
The allItems array does now contain MPMediaItemCollections, grouping is done by album. Now you can walk through the arrays.
for (MPMediaItemCollection *collection in allAlbumsArray) {
MPMediaItem *item = [collection representativeItem];
}
Thanks for the answer, here is working sample code that prints out the albums and artists in case someone needs it:
NSMutableString *outText = [[NSMutableString alloc] initWithString:#"Albums:"];
[outText appendFormat:#"\r\n count:%i",[[[MPMediaQuery albumsQuery] collections] count]];
for (MPMediaItemCollection *collection in [[MPMediaQuery albumsQuery] collections]) {
[outText appendFormat:#"\r\n -%#",[[collection representativeItem] valueForProperty:MPMediaItemPropertyAlbumTitle]];
}
[outText appendString:#"\r\n\r\n Artist:"];
for (MPMediaItemCollection *collection in [[MPMediaQuery artistsQuery] collections]) {
[outText appendFormat:#"\r\n -%#",[[collection representativeItem] valueForProperty:MPMediaItemPropertyArtist]];
}
NSLog(#"%#",[outText autorelease]);
Here you go. You can get the albums and their songs.
/// Get all albums and their songs
///
func getAllAlbums() {
let query: MPMediaQuery = MPMediaQuery.albums()
let allAlbums = query.collections
allAlbumItems?.removeAll()
guard allAlbums != nil else {
return
}
for collection in allAlbums! {
let item: MPMediaItem? = collection.representativeItem
let albumName = item?.value(forKey: MPMediaItemPropertyAlbumTitle) as? String ?? "<Unknown>"
let albumId = item!.value(forProperty: MPMediaItemPropertyAlbumPersistentID) as! NSNumber
let artistName = item?.value(forKey: MPMediaItemPropertyArtist) as? String ?? "<Unknown>"
let album = Album()
album.name = albumName
album.artistName = artistName
album.albumId = String(describing: albumId)
print("Album name: \(albumName)")
// Get all songs in this album
let mediaQuery = MPMediaQuery.songs()
let predicate = MPMediaPropertyPredicate.init(value: albumId, forProperty: MPMediaItemPropertyAlbumPersistentID)
mediaQuery.addFilterPredicate(predicate)
let song = mediaQuery.items
if let allSongs = song {
var index = 0
for item in allSongs {
let pathURL: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
if pathURL == nil {
print("#Warning!!! Track : \(item) is not playable.")
} else {
let trackInfo = SongItem()
trackInfo.index = index
trackInfo.mediaItem = item
let title = item.value(forProperty: MPMediaItemPropertyTitle) as? String ?? "<Unknown>"
let artistName = item.value(forProperty: MPMediaItemPropertyArtist) as? String ?? "<Unknown>"
trackInfo.songName = title
trackInfo.artistName = artistName
trackInfo.isSelected = false
trackInfo.songURL = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
album.songs?.append(trackInfo)
index += 1
}
}
}
// Finally add the album object to albums array
allAlbumItems?.append(album)
}
print("Total Album count: \(allAlbumItems?.count)")
}