I am trying to build a flutter plugin for the Sendbird iOS SDK. For some reason whenever I try to fetch data, I get null from a NSDictionary<NSString *,NSObject *> when I know for a fact that it is not (I have created the keys and values separately).
Most likely it's the fact that being a beginner with Swift I am doing something wrong. This is my code:
let channelMetadata = NSMutableDictionary()
// metadata is the NSDictionary<NSString *,NSObject *>
channel.getAllMetaData{ (metaData, error) in
guard let metadata = metaData, error == nil else {
// Error.
return
}
channelMetadata["status"] = metadata["status"]
channelMetadata["type"] = metadata["type"]
}
js["status"] = channelMetadata["status"]
it's:
js["status"]
Which returns null. I assume this is because I am doing something wrong with the way I am populating my empty dictionary, but I don't know what, even after searching for hours. Any help would be really appreciated.
Related
I have this code
let path = self.userDesktopDirectory + "/Library/Preferences/.GlobalPreferences.plist"
let dictRoot = NSDictionary(contentsOfFile: path)
if let dict = dictRoot{
try print(dict["AppleLocale"] as! String)
}
If the Value "AppleLocale" didnt exists the script crashes. What I must add to "catch" the Error and avoid the crash?
If the Value "AppleLocale" didnt exists the script crashes. What I
must add to "catch" the Error and avoid the crash?
depends on what's the reason for causing the crash. Mentioning that "If the Value AppleLocale didnt exists" means the the reason for the crash would be the force casting:
dict["AppleLocale"] as! String
probably, it has nothing to do with the try, it would be:
Unexpectedly found nil while unwrapping an Optional value
Means that at some point dict["AppleLocale"] could be nil or even if it contains a value as not a string it will crash (optional). You have to make sure that dict["AppleLocale"] is a valid (not nil) string, there are more than just one approach to follow for doing it, for instance you could do optional binding, like this:
let path = self.userDesktopDirectory + "/Library/Preferences/.GlobalPreferences.plist"
let dictRoot = NSDictionary(contentsOfFile: path)
if let dict = dictRoot{
if let appleLocale = dict["AppleLocale"] as? String {
print(appleLocale)
} else {
// `dict["AppleLocale"]` is nil OR contains not string value
}
}
Actually, I would assume that you don't have to deal with try for such a case.
So I know this may be a bit specific but I've been staring at my code and am unable to resolve this issue. Basically, I'm making a network call to spotify to obtain a certain playlist and pass a number that will ultimately determine the number of songs I get back. The code is basically as follows:
// A network call is made just above to return somePlaylist
let playlist = somePlaylist as! SPTPartialPlaylist
var songs: [SPTPartialTrack] = []
// load in playlist to receive back songs
SPTPlaylistSnapshot.playlistWithURI(playlist.uri, session: someSession) { (error: NSError!, data: AnyObject!) in
// cast the data into a correct format
let playlistViewer = data as! SPTPlaylistSnapshot
let playlist = playlistViewer.firstTrackPage
// get the songs
for _ in 1...numberOfSongs {
let random = Int(arc4random_uniform(UInt32(playlist.items.count)))
songs.append(playlist.items[random] as! SPTPartialTrack)
}
}
The problem comes at the portion of code that initializes random. In maybe 1 in 20 calls to this function I, for whatever, reason unwrap a nil value for playlist.items.count and can't seem to figure out why. Maybe it's something I don't understand about API calls or something else I'm failing to see but I can't seem to make sense of it.
Anyone have any recommendations on addressing this issue or how to go about debugging this?
Ok, after sleeping on it and working on it some more I seem to have resolved the issue. Here's the error handling I implemented into my code.
if let actualPlaylist = playlist, actualItems = actualPlaylist.items {
if actualItems.count == 0 {
SongScraper.playlistHasSongs = false
print("Empty playlist, loading another playlist")
return
}
for _ in 1...numberOfSongs {
let random = Int(arc4random_uniform(UInt32(actualItems.count)))
songs.append(actualPlaylist.items[random] as! SPTPartialTrack)
}
completionHandler(songs: songs)
}
else {
print("Returned a nil playlist, loading another playlist")
SongScraper.playlistHasSongs = false
return
}
I'm trying to insert a text under description column, and it keep giving me error, I think I'm having this issue because I wasn't able to use the pointer properly.. is there any one can help, I watched a number of tutorial video's as to how to setup the pointer in Parse, and that didn't solve the issue.
Thanks.
let me = self.textField.text
let query = PFQuery(className: "Store")
query.getObjectInBackgroundWithId ("product", block: {
(object: PFObject?, error: NSError?) -> Void in
if error != nil
{
print(error)
}
else if let transaction = object {
transaction["discription"] = "\(me)"
transaction.saveInBackground()
print(object!.objectForKey("discription"))
}
})
I finally got the answer, the best possible answer I got was, not store any information to the DB till all the input is done from the last page. It means you carry over the input as temp to each pages, then save it at the end... :)
I have Parse.enableLocalDatastore() in my app delegate before Parse.setApplicationId
Then I have var newPosts = PFObject(className: "Post") as a global variable.
Then I want to get 1,000 latest objects from the "Post" table from localDataStore that I enabled earlier so I do this:
var getNewPosts = PFQuery(className: "Post")
getNewPosts.fromLocalDatastore()
getNewPosts.limit = 1000
getNewPosts.orderByDescending("createdAt")
getNewPosts.findObjectsInBackgroundWithBlock {
(downloadedPosts, error) -> Void in
if downloadedPosts != nil && error == nil {
println(downloadedPosts) // I am getting table with no data
}
}
But I only get empty data rows.
If I comment out the getNewPosts.fromLocalDatastore() line results are fine.
I understand that I am missing the critical Pinning step but not sure from Parse documentation hoe and where to implement it. Can you please help?
You are getting no data....
reasons my be...
Wrong name of class (class names are case sensitive)
Data is not there in local storage
Try synchronous version of findObject: method and pin: method.
I am very new to swift and I don't know Obj C at all so many of the resources are hard to understand. Basically I'm trying to populate the dictionary with PFUsers from my query and then set PFUser["friends"] to this dictionary. Simply put I want a friends list in my PFUser class, where each friend is a PFUser and a string.
Thanks!
var user = PFUser()
var friendsPFUser:[PFUser] = []
var friendListDict: [PFUser:String] = Dictionary()
var query = PFUser.query()
query!.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(users!.count) users.")
// Do something with the found objects
if let users = users as? [PFUser] {
friendsPFUser = users
for user in friendsPFUser{
friendListDict[user] = "confirmed"
}
user["friends"] = friendListDict //this line breaks things
user.saveInBackground()
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
To be clear, this code compiles but when I add
user["friends"] = friendListDict
my app crashes.
For those who might have this issues with. "NSInternalInconsistencyException" with reason "PFObject contains container item that isn't cached."
Adding Objects to a user (such as arrays or dictionaries) for security reasons on Parse, the user for such field that will be modified must be the current user.
Try signing up and using addObject inside the block and don't forget do save it!
It helped for a similar problem I had.