All playlists seem to lack subscribers - ios

All playlists that I have checked so far has returned 0 subscribers. Am I doing something wrong? Do you need special rights to do this? I am using cocoalibspotify 2.2.0.
Here's the code:
playlistURL = [NSURL URLWithString:#"spotify:user:tunigo:playlist:14KrfXbVeyzVek6UX8jUlH"];
NSLog(#"%#", playlistURL);
[[SPSession sharedSession] playlistForURL:playlistURL callback:^(SPPlaylist *playlist){
if (playlist != nil) {
[SPAsyncLoading waitUntilLoaded:playlist timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedPlaylists, NSArray *notLoadedTracks) {
NSLog(#"Nr of subscribers: %d", [playlist.subscribers count]);
NSLog(#"========================");
}];
}
}];
Outputs this:
spotify:user:tunigo:playlist:14KrfXbVeyzVek6UX8jUlH
Playlist name: Dinner with Friends
Nr of subscribers: 0
========================

Since updating subscribers can be quite a lengthy task, it looks like SPPlaylist starts updating them once it's loaded, i.e., after SPAsyncLoading returns.
However, the subscribers property is KVO-compliant so you should be able to observe the subscribers property for changes.

Related

iOS AFNetwork 3.0: Is there a faster way to send multiple API requests and wait until all of it is finished?

I am currently using the following method to send GET API requests. This method works, but I was wondering if there is a faster way. All I need regarding requirements is to know when all of the Deleted mail has been synced. Any tips or suggestions are appreciated.
- (void)syncDeletedMail:(NSArray *)array atIdx:(NSInteger)idx {
if (idx < array.count) {
NSInteger idNumber = array[idx];
[apiClient deleteMail:idNumber onSuccess:^(id result) {
[self syncDeletedMail:array atIdx:(idx + 1)];
} onFailure:^(NSError *error){
[self syncDeletedMail:array atIdx:(idx + 1)];
}];
} else {
NSLog(#"finished");
}
}
Edit: I don't care what order it is completed (not sure if it matters in terms of speed), as long as all the API requests come back completed.
You can just send deleteMail requests at once and use dispatch_group to know when all the requests are finished. Below is the implementation,
- (void)syncDeletedMail:(NSArray *)array {
dispatch_group_t serviceGroup = dispatch_group_create();
for (NSInteger* idNumber in array)
{
dispatch_group_enter(serviceGroup);
[apiClient deleteMail:idNumber onSuccess:^(id result) {
dispatch_group_leave(serviceGroup);
} onFailure:^(NSError *error){
dispatch_group_leave(serviceGroup);
}];
}
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
NSLog(#"All email are deleted!");
});
}
Here you can see all the requests are fired at the same time so it will reduce the time from n folds to 1.
Swift Version of #Kamran :
let group = DispatchGroup()
for model in self.cellModels {
group.enter()
HTTPAPI.call() { (result) in
// DO YOUR CHANGE
switch result {
...
}
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
// UPDATE UI or RELOAD TABLE VIEW etc.
// self.tableView.reloadData()
}
I suppose your request is due to the fact that you might have huge amounts of queued delete requests, not just five or ten of them.
In this case, I'd also try and consider adding a server side API call that allows you to delete more than just one item at a time, maybe up to ten or twenty, so that you could also reduce the overhead of the network traffic you'd be generating (a single GET isn't just sending the id of the item you are deleting but also a bunch of data that will basically sent on and on again for each and every call) by grouping the mails in batches.

Seems impossible to delete a subscription in CloudKit? `-deleteSubscriptionWithID` always returns true

I'm hoping there's an experienced CloudKit guru out there, but based off my google search queries, I'm not sure if you exist. I think this may be a bug with Apple, but I can't be sure :\
I can save a subscription to my CKDatabase fine, no problems at all.
[publicDatabase saveSubscription:subscription completionHandler:^(CKSubscription *subscription, NSError *error) {
if (error)
{
//No big deal, don't do anything.
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:[subscription subscriptionID] forKey:#"SUBSCRIPTION"];
}
}];
Whenever I change a field in my record, I get a push notification, and everything is happy.
My problem is removing this subscription.
I have tried calling -deleteSubscriptionWithID:completionHandler:
As you can see in the above code snippet, I save off the subscription ID (Have also confirmed it to be the correct subscription ID by calling -fetchAllSubscriptionsWithCompletionHandler:
I passed the subscriptionID in that message, like so:
[publicDatabase deleteSubscriptionWithID:[[NSUserDefaults standardUserDefaults] objectForKey:#"SUBSCRIPTION"] completionHandler:^(NSString * _Nullable subscriptionID, NSError * _Nullable error) {
if( error ) {
NSLog(#"ERROR: %#", [error description] );
}
else
{
NSLog(#"SUCCESS: %#", subscriptionID);
}
}];
But it doesn't delete my subscription:
And no matter what I pass as the subscriptionID, there is no error and I see "SUCCESS" upon "deleting".
...so yeah. Clearly that isn't going to work.
If I manually delete the subscription through the Cloudkit Dashboard, my -fetch call properly notices that and returns an empty array:
So at this point I'm certain that I'm either deleting a subscription incorrectly in code, or it's broken and (not likely) nobody has asked on SO or any other forum that I can find?
I have also tried using a CKModifySubscriptionsOperation
CKModifySubscriptionsOperation *deleteSub = [[CKModifySubscriptionsOperation alloc] initWithSubscriptionsToSave:nil subscriptionIDsToDelete:#[[[NSUserDefaults standardUserDefaults] objectForKey:#"SUBSCRIPTION"]]];
[publicDatabase addOperation:deleteSub];
No results :(
I delete subscriptions using the database.deleteSubscriptionWithID function.
If you want to make sure that the ID is correct you could also first fetch all of them using database.fetchAllSubscriptionsWithCompletionHandler({subscriptions, error in
Then in the completion handler check if it's a valid subscription using: if let subscription: CKSubscription = subscriptionObject
And then delete one or more using: database.deleteSubscriptionWithID(subscription.subscriptionID, completionHandler: {subscriptionId, error in
Here you can see code how I delete all subscriptions:
https://github.com/evermeer/EVCloudKitDao/blob/1bfa936cb46c5a2ca75f080d90a3c02e925b7e56/AppMessage/AppMessage/CloudKit/EVCloudKitDao.swift#L897-897

How do I save thousands of objects to Parse.com? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
In my iOS app that uses Parse, some users will need to save thousand of objects in one action. I've tried iterating through the array of data and creating/saving the objects one by one, but this results in the objects saving to my data browser pretty slowly. Each object only needs to contain a few strings, so I don't understand why its taking so long to save these objects.
Is there a faster way to save thousands of objects to Parse?
Edited:
I've always used [PFObject saveAllInBackground:array block:^(BOOL succeeded, NSError *error) {}]; but....another method I have just attempted semi-successfully, was to upload a Json string as a PFFile(no 128k limit), and then use cloud code to parse it and create the necessary PFObjects. I was able to get this to work with small quantities, but unfortunately the cloud code timed out when using a large quantity. I instead opted to utilize a background job to perform the parsing. This takes a considerable amount of time before the data is completely available, but can handle the large amount of data. The upload time itself was much quicker. When using 1000 objects with 3 strings each upload was roughly .8 seconds, vs 23 seconds doing a save all in background, 5000 objects 3 strings each was only 2.5 seconds upload time. In addition to the quicker time you also get progress updates. Depending on the use-case, utilizing this alternative may work best if immediate and quick upload is important, vs making the data immediately available.
IOS Code:
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i<5; i++) {
//subclass of PFObject
Employee *employee = [Employee object];
employee.firstName = #"FName";
employee.lastName = #"LName";
employee.employeeID = #"fid54";
[array addObject:[employee dictionaryWithValuesForKeys:employee.allKeys]];
}
//Seperate class only to store the PFFiles
PFObject *testObject = [PFObject objectWithClassName:#"fileTestSave"];
testObject[#"testFile"] = [PFFile fileWithData:[NSJSONSerialization dataWithJSONObject:array options:0 error:nil]];
NSLog(#"started");
//**notice I am only saving the test object with the NSData from the JSONString**
[testObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error && succeeded) NSLog(#"succeeded");
else NSLog(#"error");
}];
Edited: Instead of saving in the beforeSave or afterSave Cloud Code which can cause timeout issues, the background job below can be run anytime. It grab all rows in the "fileTestSave" table, parses the JSON strings in those rows, and adds them to the "Person" table. Once completed it will rows from the table. All asynchronously!
var _ = require('underscore.js');
Parse.Cloud.job("userMigration", function(request, status)
{
// Set up to modify user data
Parse.Cloud.useMasterKey();
//Table called fileTestSave stores a PFFile called "testFile" which we will use an HTTPRequest to get the data. Is there a better way to get the data?
//This PFFile stores a json string which contains relavent data to add to the "Person" table
var testFileSave = Parse.Object.extend("fileTestSave");
var query = new Parse.Query(testFileSave);
query.find().then(function(results)
{
//Generate an array of promises
var promises = [];
_.each(results, function(testFileSaveInstance){
//add promise to array
promises.push(saveJsonPerson(testFileSaveInstance));
});
//only continue when all promises are complete
return Parse.Promise.when(promises);
}).then(function()
{
// Set the job's success status
console.log("Migration Completed NOW");
status.success("Migration completed");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
});
function saveJsonPerson(fileTestSave)
{
//Get the pffile testfile
var testFile = fileTestSave.get("testFile");
//get the fileURL from the PFFile to generate the http request
var fileURL = testFile["url"]();
//return the promise from the httpRequest
return Parse.Cloud.httpRequest({
method:"GET",
url: fileURL
}).then(function(httpResponse){
//return the promise from the parsing
return parsehttpResponse(httpResponse,fileTestSave);
},
function(error){
console.log("http response error");
}
);
}
function parsehttpResponse(httpResponse,fileTestSave)
{
var jsonArray = eval( '(' + httpResponse.text + ')' );
var saveArray =[];
//parse each person in the json string, and add them to the saveArray for bulk saving later.
for (i in jsonArray)
{
var personExtend = Parse.Object.extend("Person");
var person = new personExtend();
person.set("classDiscriminator",jsonArray[i]["classDiscriminator"]);
person.set("lastName",jsonArray[i]["lastName"]);
person.set("firstName",jsonArray[i]["firstName"]);
person.set("employeeID",jsonArray[i]["employeeID"]);
saveArray.push(person);
};
//return the promise from the saveAll(bulk save)
return Parse.Object.saveAll(
saveArray
).then(function(){
//return the promise from the destory
return fileTestSave.destroy(
).then(function(){
},function(error){
console.log("error destroying");
}
);
},function(error){
console.log("Error Saving");
}
);
}
Old Cloud Code that timed out as reference:
Parse.Cloud.afterSave("fileTestSave", function(request) {
//When accessing PFFiles you don't get the actual data, there may be an easier way, but I just utitlized an HTTPRequest to get the data, and then continued parsing.
var file = request.object.get("testFile");
var fileURL = file["url"]();
console.log("URL:"+fileURL);
Parse.Cloud.httpRequest({
method:"GET",
url: fileURL,
success: function(httpResponse)
{
var jsonArray = eval( '(' + httpResponse.text + ')' );
var saveArray =[];
for (i in jsonArray)
{
var personExtend = Parse.Object.extend("Person");
var person = new personExtend();
//May be a better way to parse JSON by using each key automatically, but I'm still new to JS, and Parse so I set each individually.
person.set("classDiscriminator",array[i]["classDiscriminator"]);
person.set("lastName",array[i]["lastName"]);
person.set("firstName",array[i]["firstName"]);
person.set("employeeID",array[i]["employeeID"]);
saveArray.push(person);
};
Parse.Object.saveAll(saveArray,
{
success: function(list) {
// All the objects were saved.
},
error: function(error) {
// An error occurred while saving one of the objects.
},
});
},
error: function(httpResponse) {
console.log("http response error");
}
});
});
Another method for uploading thousands of objects in the background, again this takes some time but can be sized to avoid timing out, as arrays are saved in chunks recursively. I've had no problem saving 10k+ items. Implemented as a category, just enter how many objects at a time you want save at a time, it will save them in the background serially, and recursively until all objects are saved, it also features progress updating via a separate block.
// PFObject+addOns.h
#import <Parse/Parse.h>
#interface PFObject (addOns)
+(void)saveAllInBackground:(NSArray *)array chunkSize:(int)chunkSize block:(PFBooleanResultBlock)block progressBlock:(PFProgressBlock)progressBlock;
#end
#import "PFObject+addOns.h"
#interface PFObject (addOns_internal)
+(void)saveAllInBackground:(NSArray *)array chunkSize:(int)chunkSize block:(PFBooleanResultBlock)block trigger:(void(^)())trigger;
#end
#implementation PFObject (addOns)
+(void)saveAllInBackground:(NSArray *)array chunkSize:(int)chunkSize block:(PFBooleanResultBlock)block progressBlock:(PFProgressBlock)progressBlock
{
unsigned long numberOfCyclesRequired = array.count/chunkSize;
__block unsigned long count = 0;
[PFObject saveAllInBackground:array chunkSize:chunkSize block:block trigger:^() {
count++;
progressBlock((int)(100.0*count/numberOfCyclesRequired));
}];
}
+(void)saveAllInBackground:(NSArray *)array chunkSize:(int)chunkSize block:(PFBooleanResultBlock)block trigger:(void(^)())trigger
{
NSRange range = NSMakeRange(0, array.count <= chunkSize ? array.count:chunkSize);
NSArray *saveArray = [array subarrayWithRange:range];
NSArray *nextArray = nil;
if (range.length<array.count) nextArray = [array subarrayWithRange:NSMakeRange(range.length, array.count-range.length)];
[PFObject saveAllInBackground:saveArray block:^(BOOL succeeded, NSError *error) {
if(!error && succeeded && nextArray){
trigger(true);
[PFObject saveAllInBackground:nextArray chunkSize:chunkSize block:block trigger:trigger];
}
else
{
trigger(true);
block(succeeded,error);
}
}];
}
#end
I think you should be able to do this with sending the save process in quantities of five into the background, so to speak fork it, "thread" it, as apple would refer to it.
here is the link to apples ios threading guides.
I have not used it yet, but I will soon need it as well, as I'm working on a massive database app.
here's the link
https://developer.apple.com/library/mac/Documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html
If you have an array of objects, you can use saveAllInBackgroundWithBlock. This method takes an array of PFObjects as its argument:
https://parse.com/docs/ios/api/Classes/PFObject.html#//api/name/saveAllInBackground:block:
For the faster processing, you can use the parse cloud code, whihc is simply a javascript. You can create a function which takes the array of the data as argument and then in function, you can save the objects.
Parse cloud code has better processing speed than the native one.
For its use, you can refer :
https://parse.com/docs/cloud_code_guide
https://parse.com/docs/js_guide

Fetching Gmails Via Mailcore 2: Thread ID vs Message ID vs UID

I have an iPad application that allows users to access their Gmail accounts using Mailcore2. I thought I had an understanding of the difference between Gmail's Thread Id, Message ID and UID until I looked closely at what Mailcore2 is returning to me when I perform a message fetch operation. I am hoping someone can clarify my confusion.
Here is what I think I know from the Gmail docs:
1) A thread ID groups together messages (which have their own message IDs and UIDs) that are part of the same conversation
2) A UID is specific to a message and is unique only to the folder which contains it
3) A message ID is specific to a message and is unique across all folders of an account
I am also making the following assumptions:
1) A thread has a thread ID and is a collection of messages. A thread does not have a message ID or a UID.
2) A message has a message ID, UID and thread ID (even if it is the only message in a thread)
3) Fetching messages by UID fetches MESSAGES which have a UID that falls in the requested range of UIDs.
4) Messages that belong to the same thread will have different UIDs and message IDs but the same Thread ID.
Ok, so assuming that the above is correct, I would think that during a typical fetch of messages in Mailcore2 by UID, I would receive an array of emails, and from those emails I could look at their thread ID, for example and reconstruct threads on the client side. However, I seem to get back threads rather than emails. Additionally, each thread I get does not necessarily contain all its 'child' messages.
So for example, if I have two threads in my inbox, each containing five messages, Mailcore returns to me an array of 2 "emails" in the form of MCOIMAPMessages. And each "email" has one thread ID, one message ID and one UID. So I am not sure how to access contained emails on these two threads. I see that there is a references array... but inspecting this object doesn't reveal anything useful. When I log the contents of each thread, I get only part of the contents - say 4 out of the 5 messages on the thread. Not sure if this is Mailcore or an error in my saving process due to my incomplete understanding of how this is all working.
Here is my code to fetch messages:
//create fetch operation to get first (10) messages in folder (first fetch is done by sequence number, subsequent fetches are done by UID
uint64_t location = MAX([info messageCount] - DefaultPageSize + 1, 1);
uint64_t size = serverMessageCount < DefaultPageSize ? serverMessageCount - 1 : DefaultPageSize - 1;
MCOIndexSet *numbers = [MCOIndexSet indexSetWithRange:MCORangeMake(location, size)];
MCOIMAPMessagesRequestKind kind = MCOIMAPMessagesRequestKindUid |
MCOIMAPMessagesRequestKindFullHeaders |
MCOIMAPMessagesRequestKindFlags |
MCOIMAPMessagesRequestKindHeaders |
MCOIMAPMessagesRequestKindInternalDate;
if ([capabilities containsIndex:MCOIMAPCapabilityGmail]) {
kind |= MCOIMAPMessagesRequestKindGmailLabels | MCOIMAPMessagesRequestKindGmailThreadID | MCOIMAPMessagesRequestKindGmailMessageID;
self.gmailCapability = YES;
}
fetchLatestEmails ([self.imapSession fetchMessagesByNumberOperationWithFolder:folder.folderId requestKind:kind numbers:numbers]);
//perform fetch
void (^fetchLatestEmails)(MCOIMAPFetchMessagesOperation *) = ^(MCOIMAPFetchMessagesOperation *fetchOperation) {
[fetchOperation start:^(NSError *error, NSArray *emails, MCOIndexSet *vanishedMessages) {
if (nil != error) {
failure(error);
NSLog(#"the fetch error is %#", error);
return;
}
[self.dataManager performBatchedChanges:^{
if ([emails count] !=0) {
MCOIndexSet *savedThreadIds = [[MCOIndexSet alloc]init];
for (MCOIMAPMessage *email in emails) {
//do stuff with emails
Thread *thread = [self.dataManager fetchOrInsertNewThreadForFolder:folder threadId:email.gmailThreadID ?: email.gmailMessageID ?: email.uid error:nil];
if (nil != thread) {
[savedThreadIds addIndex:thread.threadId];
[self.dataManager updateOrInsertNewEmailForThread:thread uid:email.uid messageId:email.gmailMessageID date:email.header.receivedDate subject:email.header.subject from:email.header.from.mailbox to:[email.header.to valueForKey:#"mailbox"] cc:[email.header.cc valueForKey:#"mailbox"] labels:labels flags:flags error:nil];
}
if (nil != error) {
failure(error);
return;
}
}
[savedThreadIds enumerateIndexes:^(uint64_t threadId) {
[self.dataManager updateFlagsForThreadWithThreadId:threadId inFolder:folder];
}];
}
NSError *folderUpdateError;
[self.dataManager updateFolder:folder withMessageCount:serverMessageCount error:&folderUpdateError];
} error:&error];
if (nil == error) {
[self refreshFolder:folder success:^{
success();
}failure:^(NSError *error) {
}];
} else {
failure(error);
}
}];
};
Clearly something is amiss here in terms of my understanding of either Gmail or Mailcore2. If anyone can point out my misunderstanding I would appreciate it.
After opening an issue with Mailcore and a bit of research I have found the answers to my own questions.
First, my above assumptions about UID, gmailMessageID and gmailThreadID are correct. The confusion was in my looking at the Gmail conversation view of my email account on the web, and expecting my Mailcore fetch to match it. This does not happen because the conversation view, as the name implies, stitches together ALL messages of a conversation, even those that were replies to an incoming message in the inbox - ordinarily such messages would be found in the 'sent' or 'all mail' folder. In other words, what is fetched from Mailcore looks incomplete only because it is fetching what is ACTUALLY in your inbox (or whatever folder you are fetching messages from). This does NOT include replies to incoming messages. In order to include such messages (i.e. to re-create Gmail's conversation view) I understand that one must fetch sent messages from 'all mail' (or I suppose 'sent' mail) by doing a search operation using the gmailThreadID of the message of interest.
Switching the conversation view to 'off' for my Gmail account on the web while testing my Mailcore fetch operations makes testing much clearer.
Found the answer
for getting gmailThreadID we need to add MCOIMAPMessagesRequestKindGmailThreadID. in Fetch request like below example.
MCOIMAPMessagesRequestKind requestKind = (MCOIMAPMessagesRequestKind)
(MCOIMAPMessagesRequestKindHeaders | MCOIMAPMessagesRequestKindStructure |
MCOIMAPMessagesRequestKindInternalDate | MCOIMAPMessagesRequestKindHeaderSubject |
MCOIMAPMessagesRequestKindFlags | MCOIMAPMessagesRequestKindGmailThreadID);

Kinvey iOS query all users

From Kinvey documentation this is the method to use for querying users:
To query the user collection we recommend instead using
+[KCSUserDiscovery lookupUsersForFieldsAndValues:completionBlock:progressBlock:]. This
method allows you to supply a dictionary of exact matches for special
fields.
Fields for lookup:
KCSUserAttributeUsername
KCSUserAttributeSurname
KCSUserAttributeGivenname
KCSUserAttributeEmail
KCSUserAttributeFacebookId
[KCSUserDiscovery lookupUsersForFieldsAndValues:#{ KCSUserAttributeSurname : #"Smith"}
completionBlock:^(NSArray *objectsOrNil, NSError *errorOrNil) {
if (errorOrNil == nil) {
//array of matching KCSUser objects
NSLog(#"Found %d Smiths", objectsOrNil.count);
} else {
NSLog(#"Got An error: %#", errorOrNil);
}
}
progressBlock:nil];
But if I send empty dictionary, I get an error. So what to put in dictionary to get all the users?
Thank you guys, happy holidays
To get all the users, you can use the regular app data querying API.
For example,
KCSAppdataStore* store = [KCSAppdataStore storeWithCollection:[KCSCollection userCollection] options:nil];
[store queryWithQuery:[KCSQuery query] withCompletionBlock:^(NSArray *objectsOrNil, NSError *errorOrNil) {
//handle completion
} withProgressBlock:nil];
This will get a list of all the users the active user has permission to access.

Resources