realmOC can't update data - swift

addobject is success. but i want to update data. After realm.beginWriteTransaction() executes, breakpoint can't continue execute backup.quanId = 5, it's like just jump over.
class YQQuanBackup: RLMObject {
dynamic var groupId:Int = 0
dynamic var quanId:Int = 0
dynamic var content:String = ""
}
GCDBlock.async(.Default) {
let results:RLMResults = YQQuanBackup.objectsWhere("groupId == %d", self.groupInfo!.groupId)
let quanBackup = results.firstObject() as? YQQuanBackup
guard let backup = quanBackup else { return }
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
backup.quanId = 5
backup.content = YQRichTextUtil.richTextToPublishText(self.textView.attributedText, uploadedImageUrls: self.uploadedImageUrls)
do {
try realm.commitWriteTransaction()
} catch {
print(error)
}
}

Related

CoreData batch insert Entities with Relationship

Is there anyway to insert entities with relationship? I get error "Illegal attempt to establish a relationship 'content' between objects in different contexts"
addUsers(users: [userData])
func addUsers(users: [User]) {
let taskContext = container.viewContext
taskContext.perform {
let batchInsertRequest = self.newBatchInsertRequest(with: users)
if let fetchResult = try? taskContext.execute(batchInsertRequest),
let batchInsertResult = fetchResult as? NSBatchInsertResult,
let success = batchInsertResult.result as? Bool, success {
return
}
}
}
crash happens in below code
private func newBatchInsertRequest(with users: [Users]) -> NSBatchInsertRequest {
var index = 0
let total = message.count
let batchInsertRequest = NSBatchInsertRequest(entity: WaUser.entity(), managedObjectHandler: { managedObject in
guard index < total else { return true }
let user = users[index]
if let waUser = managedObject as? WaUser {
waUser.name = user.name
let waUserInfo = waUserInfo(context: self.container.viewContext)
waUserInfo.pass = "12345"
waUserInfo.key = "asdfgh"
waUser.info = waUserInfo **//crash occurs here**
}
index += 1
return false
})
return batchInsertRequest
}

Data from csv file won't show up when called in list on Swift

So I'm learning to import data from csv files to my swift project.
I'm trying to see everything is imported correctly by displaying some of the items in a list. However, even though I'm getting no errors at all, the list doesn't show up.
Can anyone help me out?
My csv setup code:
import Foundation
struct Leden: Identifiable {
var voorNaam: String = ""
var achterNaam: String = ""
var functie: String = ""
var id = UUID()
init (raw: [String]) {
voorNaam = raw[0]
achterNaam = raw[1]
functie = raw[2]
}
}
func loadCSV(from csvName: String) -> [Leden] {
var csvToStruct = [Leden]()
guard let filePath = Bundle.main.path(forResource: csvName, ofType: "csv") else {
return[]
}
var data = ""
do {
data = try String(contentsOfFile: filePath)
} catch {
print(error)
return[]
}
var rows = data.components(separatedBy: "\n")
let columnCount = rows.first?.components(separatedBy: ",").count
rows.removeFirst()
for row in rows {
let csvColumns = row.components(separatedBy: ",")
if csvColumns.count == columnCount {
let ledenStruct = Leden.init(raw: csvColumns)
csvToStruct.append(ledenStruct)
}
}
return csvToStruct
}
My code to make the csv items appear in a list:
struct PraesidiumView: View {
var individu = loadCSV(from: "Ledenlijst")
var body: some View {
NavigationView{
List(individu){Leden in
Text(Leden.voorNaam)
}
.navigationTitle("Praesidium")
}
}
}
try to implement this way, you also learn mvvm way.
class PraesidiumViewModel: ObservableObject {
#Public var ledens: [Leden] = []
func loadCSV() {
// ...
self.ledens = csvToStruct
}
}
struct PraesidiumView: View {
#StateObject var viewModel = PraesidiumViewModel()
var body: some View {
NavigationView {
List(viewModel.ledens){ leden in
Text(leden.voorNaam)
}
.navigationTitle("Praesidium")
}.onAppear() {
viewModel.loadCSV()
}
}
}
you could try something like this (untested) to read your csv data:
func loadCSV(from csvName: String) -> [Leden] {
var csvToStruct = [Leden]()
guard let filePath = Bundle.main.path(forResource: csvName, ofType: "csv") else {
return[]
}
var data = ""
do {
data = try String(contentsOfFile: filePath)
} catch {
print(error)
return []
}
var rows = data.components(separatedBy: "\n")
if let firstRow = rows.first {
rows.removeFirst()
for row in rows {
let csvColumns = row.components(separatedBy: ",")
if csvColumns.count >= 3 {
let ledenCol = Array(csvColumns[0..<3])
let ledenStruct = Leden(raw: ledenCol)
csvToStruct.append(ledenStruct)
}
}
}
return csvToStruct
}
So I find a solution.
I just restarted following the tutorial and this time, I gave all parameters the exact same name as they did in the tutorial and that worked.
So I just messed up because of probably a wrong name assigned to a certain parameter.

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)
}
}

How to get and add to Syncano reference to user_profile

as in the title I have problem how adds to syncano reference to user_profile,
If someone could tell me a hint?
So this is my code:
func saveName() {
let Uerextra = userextra()
Uerextra.name = (self.dict.objectForKey("first_name") as? String)!
Uerextra.lastName = (self.dict.objectForKey("last_name") as? String)!
Uerextra.avatarUrl = self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as! String
Uerextra.FacebookId = (self.dict.objectForKey("id") as? String)!
Uerextra.saveWithCompletionBlock { error in
if error != nil {
print(error)
}
}
}
And I need 1 extra field with reference to user id.
This is my class:
class userextra : SCDataObject {
var name = ""
var lastName = ""
var avatarUrl = ""
var FacebookId = ""
var user: SCUserProfile! = nil
}
Ok after several attempts I managed to save this reference to Syncano.
This is my code:
func saveName() {
user_profile.please().enumaratePagesWithPredicate(nil, parameters: [SCPleaseParameterPageSize : 25]) {shouldStop, s_data, error in
guard error == nil else {
return
}
if let s_data = s_data as? [user_profile] {
for user in s_data {
let uzytkownik = user
let Uerextra = userextra()
Uerextra.name = (self.dict.objectForKey("first_name") as? String)!
Uerextra.lastName = (self.dict.objectForKey("last_name") as? String)!
Uerextra.avatarUrl = self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as! String
Uerextra.FacebookId = (self.dict.objectForKey("id") as? String)!
Uerextra.user = uzytkownik
Uerextra.saveWithCompletionBlock { error in
if error != nil {
print(error)
}
}
}
}
}
}
and user_profile class:
class user_profile: SCUserProfile {
var id = 0
var Name = ""
var Surename = ""
}
Most important is register class in app delegate
SCUser.registerClassWithProfileClass(userextra.self)
SCUser.registerClassWithProfileClass(user_profile.self)

Excess memory usage swift

I'm building a today extension for iOS and I'm confused why this function keeps on using more and more memory.
See the code below:
func loadActivePlayer() {
kodi.getActivePlayer {
(response) in
let result = JSON(response)
let activePlayer = ActivePlayer()
if let playerid = result["result"][0]["playerid"].int {
activePlayer.playerid = playerid
}
if let type = result["result"][0]["type"].string {
activePlayer.type = type
}
if(activePlayer.isEmpty()) {
self.loadActivePlayer()
}
else {
self.enablePlaybackButtons(true)
self.activePlayer = activePlayer
self.kodi.getItem(activePlayer.playerid) {
(response) in
var result = JSON(response)
var item = Item()
if let id = result["result"]["item"]["id"].int {
item.id = id
}
if let type = result["result"]["item"]["type"].string {
item.type = type
}
if let label = result["result"]["item"]["label"].string {
item.label = label
}
if let title = result["result"]["item"]["title"].string {
item.title = title
}
if let season = result["result"]["item"]["season"].int {
item.season = season
}
if let episode = result["result"]["item"]["episode"].int {
item.episode = episode
}
if let showtitle = result["result"]["item"]["showtitle"].string {
item.showtitle = showtitle
}
dispatch_async(dispatch_get_main_queue()) {
self.itemTitleLabel.text = item.title
self.itemShowTitleLabel.text = item.showtitle
self.itemSeasonEpisodeLabel.text = "S\(item.season)E\(item.episode)"
}
self.loadActivePlayer()
}
}
}
When it goes in the if(activePlayer.isEmpty())
the memory usage increases and increases and increases, quite irritating.
But when it goes into the else, the memory usage stays almost the same, it does not increase significantly.
Can anyone help me understand why this is happening?
Thanx in advance!