loadPlayersForIdentifiers will not accept my array - ios

i have this playersIDArray with playerID´s in Strings and give it the loadPlayersForIdentifiers classMethod. but i´ll get an error when i call this method. the string are not nil. i already checked this. in the documentation i read the method expects an Array with playerID-Strings. why is this not working?
NSArray * playersIDArray = #[ self.userIDString1, self.userIDString2, self.userIDString3, self.userIDString4 ];
[GKPlayer loadPlayersForIdentifiers:playersIDArray withCompletionHandler:^(NSArray *players, NSError *error) {
if (players != nil) {
GKPlayer *playerGlobal1 = [players objectAtIndex:0];
GKPlayer *playerGlobal2 = [players objectAtIndex:1];
GKPlayer *playerGlobal3 = [players objectAtIndex:2];
GKPlayer *playerGlobal4 = [players objectAtIndex:3];
self.globalPlayersArray = #[ playerGlobal1, playerGlobal2, playerGlobal3, playerGlobal4 ];
NSLog(#"GKPLAYER ARRAY: %#",self.globalPlayersArray);
}
if (error) {
NSLog(#"ERROR: %#", error);
}
}];

Related

Is it possible to create a dispatch_async(dipatch_get_main_queue(), ^{}); with a completion go get when the dispatch block is finished?

I have a piece of code that execute a coredata update of the database, and I would like to know when that block is finished. Is there a way to get it knowing when the coredata has finished to update the tables?
Main function:
NSMutableArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
[self parseAndAddLovAll:responseArray toArray:self.objects];
});
Function used in dispatch:
- (void)parseAndAddLovAll:(NSMutableArray*)responseArray toArray:(NSMutableArray*)destinationArray
{
NSError *error;
DB_ListOfValue_manage *elements_to_store = [[DB_ListOfValue_manage alloc] init];
NSManagedObjectContext * context = [elements_to_store managedObjectContext];
for (int index=0; index < [responseArray count]; index++)
{
NSDictionary * responseArray2 = [[NSDictionary alloc] initWithDictionary:responseArray[index]];
NSString * table_to_store = [[NSString alloc] initWithString:[responseArray2 objectForKey:#"table"]];
NSArray * lignes = [[NSArray alloc] initWithObjects:[responseArray2 objectForKey:#"lignes"], nil];
id value;
// Check if LOV table or contact table
if ((([#"Table_contact" compare:table_to_store])!=NSOrderedSame)&&
(([#"Table_event" compare:table_to_store])!=NSOrderedSame))
{
for (NSDictionary * item in lignes[0])
{
value = [item objectForKey:#"codeevent"];
if ([value isEqualToNumber:[NSNumber numberWithInt:EVENT_ID]])
{//FIXME: bug to check when SYNC
elements_to_store = (DB_ListOfValue_manage*)[NSEntityDescription insertNewObjectForEntityForName:table_to_store inManagedObjectContext:context];
elements_to_store.code_event = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"id"];
elements_to_store.id = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"used"];
elements_to_store.used = [value isKindOfClass:[NSNull class]] ? #"" : value;
if (![context save:&error]) {
#ifdef DEBUG
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
#endif
}
else{
#ifdef DEBUG
NSLog(#"Data saved to DB, table %# %# %#", table_to_store, elements_to_store.label1, elements_to_store.label2);
#endif
}
}
}
}
}
}

List contacts with phone numbers

I'd like to fetch (in iOS using Objective-C) only the contacts that have a phone number, but how can I do that? I'm trying to form the predicate as in the code below, but obviously that doesn't work.
contacts = [contactStore unifiedContactsMatchingPredicate:[NSPredicate predicateWithFormat:#"phoneNumbers <> nil"] keysToFetch:KEYS error:nil];
So, what is the correct way of doing this? Thanks for any help!
#import <Contacts/Contacts.h>
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
request.sortOrder = CNContactSortOrderGivenName;
request.unifyResults = YES;
NSError *error;
__block NSString* email;
BOOL success = [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop)
{
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *fullName;
NSString* phone;
// for (CNContact *contact in cnContacts) {
DeviceContact *aContact = [DeviceContact new];
// copy data to my custom Contacts class.
NSString *firstName = contact.givenName;
NSString *lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
if ([firstName trim].length > 0) {
aContact.nameForSorting = firstName; // 141116
}else if ([lastName trim].length>0 && aContact.nameForSorting.length<=0) {
aContact.nameForSorting = lastName; // 141116
}
aContact.name = fullName;
if (contact.phoneNumbers!=nil && [contact.phoneNumbers count]>0) {
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [CommonUtils removeAllSpecialCharactersFromPhoneNumber:[label.value stringValue]];
if ([phone length] > 0) {
[aContact.phoneNumber addObject:phone];
}
}
}
////Get all E-Mail addresses from contacts
/// if ([CommonUtils checkIsNullObject:[contact emailAddresses]] && [[contact emailAddresses] count]>0) {
for (CNLabeledValue *label in contact.emailAddresses) {
email = label.value;
if ([email length] > 0)
{
[aContact.email addObject:email];
}
}
// }
// 141116
if ([aContact.name trim].length <= 0) {
if (aContact.email.count>0) {
aContact.name = [aContact.email objectAtIndex:0];
}else if (aContact.phoneNumber.count>0){
aContact.name = [aContact.phoneNumber objectAtIndex:0];
}
}
if ([aContact.nameForSorting trim].length <= 0){
if (aContact.email.count>0) {
aContact.nameForSorting = [aContact.email objectAtIndex:0];
}else if (aContact.phoneNumber.count>0){
aContact.nameForSorting = [aContact.phoneNumber objectAtIndex:0];
}
}
[self.arrAllContacts addObject:aContact];
}
}];
if(success){
dispatch_async(dispatch_get_main_queue(), ^{
[CommonUtils hideLoader];
completionhandler(self.arrAllContacts);
});
}
}
else
{
// [CommonUtils showAlertMessageWithMessage:#"fdfdggfsgfdgfd" withDelegate:self withCancelTitle:OKAY isOtherButton:NO withOtherButtonTitle:nil withTag:0];
[CommonUtils hideLoader];
}
}];
use following method and import
#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h>
-(void)contactsDetailsFromPhoneContactBook{
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey,CNContactGivenNameKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *fullName;
NSString *firstName;
NSString *lastName;
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[self.contactsArray addObject:fullName];
NSLog(#"working or not %#",self.contactsArray);
}
}
}
}];
}
Filtering out the contacts that don't have a phone number (or some other property) is not possible. In the docs we read:
CNContact Predicates
Predicates to match contacts. You can only use these predicates
with CNContactStore and CNContactFetchRequest.
predicateForContactsMatchingName: Returns a predicate to find the contacts matching the specified name.
predicateForContactsWithIdentifiers: Returns a predicate to find the contacts matching the specified identifiers.
predicateForContactsInGroupWithIdentifier: Returns a predicate to find the contacts that are members in the specified group.
predicateForContactsInContainerWithIdentifier: Returns a predicate to find the contacts in the specified container.
And additionally:
Compound predicates are not supported.
So, the only way to do the filtering would be to omit adding to the result array the contacts with no phone numbers. That could be done, for example, in the block of the enumerateContactsWithFetchRequest.

Incompatible pointer types sending 'NSArray<GKPlayer *> *' to parameter of type 'NSArray<NSString*> * _Nonnull'

- (void)lookupPlayers {
NSLog(#"Looking up %lu players...", (unsigned long)match.players.count);
// Error on the below line
[GKPlayer loadPlayersForIdentifiers:match.players withCompletionHandler:^(NSArray *players, NSError *error) { {
if (error != nil) {
NSLog(#"Error retrieving player info: %#", error.localizedDescription);
matchStarted = NO;
[delegate matchEnded];
} else {
// Populate players dict
self.playersDict = [NSMutableDictionary dictionaryWithCapacity:players.count];
for (GKPlayer *player in players) {
NSLog(#"Found player: %#", player.alias);
[playersDict setObject:player forKey:player.playerID];
}
// Notify delegate match can begin
matchStarted = YES;
[delegate matchStarted];
}
}];
Read the docs for GKPlayer loadPlayersForIdentifiers:withCompletionHandler:. The array of identifiers needs to be an array of NSString but you are passing in an array of GKPlayer.
You can do this to get an array of player ids from the array of players:
NSArray *playerIds = [match.players valueForKey:#"playerID"];
Then pass playerIds instead of match.players to loadPlayersForIdentifiers:withCompletionHandler:.

Parse JSON array in Objective-C

I have managed to extract the following array (which I am dumping to console) from some json. How can I get and print out the value for one of the elements, i.e. task?
Objective-C:
NSArray *array = [dict objectForKey:#"row"];
NSLog(#"array is: %#",array);
Console output:
array is: {
0 = 1;
1 = "send email";
2 = "with attachment";
ltask = "with attachment";
task = "send email";
userid = 1;
}
array looks like it is actually an NSDictionary, so reference the key to get the value for it.
NSLog(#"Task: %#", array[#"task"]);
the variable array doesn't seem to be NSArray . Does this work for you?
id array = [dict objectForKey:#"row"];
if([array isKindOfClass:[NSDictionary class]]){
NSLog(#"Value of task %#",array[#"task"]);
}
From the log, it looks like the output is an NSDictionary object, so to get the value of task key just do this
NSDictionary *myDict = dict[#"row"];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
if you want to confirm just check the class type using isKindOfClass: method
if([dict[#"row"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *myDict = dict[#"row"];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
} else if([dict[#"row"] isKindOfClass:[NSArray class]]) {
NSArray *myArray = dict[#"row"];
NSDictionary *myDict = myArray[0];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
}
try
if ([[dictionary allKeys] containsObject:#"row"]) {
NSObject *objRow = dictionary[#"row"];
if(objRow){
if([objRow isKindOfClass:[NSArray class]]){
NSArray *arr = (NSArray *)objRow;
....
}
if([objRow isKindOfClass:[NSDictionary class]]){
NSDictionary *dic = (NSDictionary *)objRow;
....
}
}
}

STTwitterAPI to pull number of tweets,followers and following?

I am trying to create a profile inside my application to show only his twitter profile. So far I do have the time line working but I don't have the number counter for the tweets,followers and following. I'm pretty sure I can use something what my code looks like but just don't know how, any help? Thanks
Code:
STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:#"ConsumerKey"
consumerSecret:#"consumerSecret"];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
[twitter getUserTimelineWithScreenName:#"MikesiOSHelp"
successBlock:^(NSArray *statuses) {
self.twitterFeed = [NSMutableArray arrayWithArray:statuses];
[self->tableView reloadData];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];
You should check out their demo application.
Your request for finding the followers of a user is explicitly covered in the CLI demo:
typedef void (^AllFollowersBlock_t)(NSArray *allFollowers);
void getFollowers(STTwitterAPI *twitter,
NSString *screenName,
NSMutableArray *followers,
NSString *cursor,
AllFollowersBlock_t allFollowersBlock) {
if(followers == nil) followers = [NSMutableArray array];
NSMutableDictionary *md = [NSMutableDictionary dictionary];
md[#"screen_name"] = screenName;
if(cursor) md[#"cursor"] = cursor;
md[#"skip_status"] = #"1";
md[#"include_user_entities"] = #"0";
[twitter getResource:#"followers/list.json"
baseURLString:kBaseURLStringAPI_1_1
parameters:md
downloadProgressBlock:^(id json) {
//
} successBlock:^(NSDictionary *rateLimits, id response) {
NSArray *users = nil;
NSString *previousCursor = nil;
NSString *nextCursor = nil;
if([response isKindOfClass:[NSDictionary class]]) {
users = [response valueForKey:#"users"];
previousCursor = [response valueForKey:#"previous_cursor_str"];
nextCursor = [response valueForKey:#"next_cursor_str"];
}
NSLog(#"-- users: %#", #([users count]));
NSLog(#"-- previousCursor: %#", previousCursor);
NSLog(#"-- nextCursor: %#", nextCursor);
[followers addObjectsFromArray:users];
if([nextCursor integerValue] == 0) {
allFollowersBlock(followers);
return;
}
/**/
NSString *remainingString = [rateLimits objectForKey:#"x-rate-limit-remaining"];
NSString *resetString = [rateLimits objectForKey:#"x-rate-limit-reset"];
NSInteger remainingInteger = [remainingString integerValue];
NSInteger resetInteger = [resetString integerValue];
NSTimeInterval timeInterval = 0;
if(remainingInteger == 0) {
NSDate *resetDate = [[NSDate alloc] initWithTimeIntervalSince1970:resetInteger];
timeInterval = [resetDate timeIntervalSinceDate:[NSDate date]] + 5;
}
NSLog(#"-- wait for %# seconds", #(timeInterval));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
getFollowers(twitter, screenName, followers, nextCursor, allFollowersBlock);
});
} errorBlock:^(NSError *error) {
NSLog(#"-- error: %#", error);
}];
}

Resources