NSArray and NSDictionary add duplicate objects - nsarray

When adding objects to NSArray or NSDictionary, my app only shows a duplicate of the last entry.
I get the data and send it to the observer...
[[NSNotificationCenter defaultCenter] postNotificationName:#"xmlFinishedLoading" object:self userInfo:[NSDictionary dictionaryWithObject:currentEventObject forKey:#"notifKey"]];
This code is ran when observer receives notification...
-(void)populateCurrentEventsTableView:(NSDictionary *)events
{
NSDictionary *info = [events valueForKey:#"userInfo"];
Event *evt = [info valueForKey:#"notifKey"];
if (self.eventDictionary == nil) {
self.eventDictionary = [[NSMutableDictionary alloc]init];
}
[self.eventList addObject:evt];
NSString *key = [NSString stringWithFormat:#"%i",[eventList count] - 1];
[self.eventDictionary setValue:evt forKey:key];
NSLog(#"events description = %#",evt.eventDescription);
[self.tableView reloadData];
}
TableView reloaded with this code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ActivitiesList";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSUInteger row = [indexPath row];
NSString *rowKey = [NSString stringWithFormat:#"%i",row];
Event *evt = [eventDictionary objectForKey:rowKey];
cell.textLabel.text = evt.eventDescription;
cell.detailTextLabel.text = evt.eventSecondaryDescription;
return cell;
}
The NSLog that displays event description is fine it shows different entries as they come. However if I were to display the entries of eventDictionary, it shows same entry. Any help?

More containing code would be helpful, what you've got looks good to me. What method does this code appear in? Is it possible that self.eventDictionary is being erased each time you come back with a userInfo object to populate it with?

Related

PHImageManager.default().requestAVAsset for video

i have an big problem with my situation
my main problem is i need fetch video one by one do some operation on the video name and save it to the file system and again fetch another video do some operation on the video name and save it to the file system through the loop of asset the problem is completion handler prevent me do that because it saving all videos together without i do any editing and changing the name this save all videos i think it is working on background thread please any help to fix this problem i need handle fetch video one by one
this is my code
for asset in arrayOfAssets {
if asset.mediaType == .video {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (AVAsset, AVAudio, info) in
// i need access to this place so i can fetch the video one by one and working with the AVAsset
})
}else{
let imageOp = PHImageRequestOptions()
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width:125,height:125), contentMode: .aspectFit, options: imageOp, resultHandler: { (img, info) in
print(img!)
})
}
}
i think this one is related to your query
for Vedios
How Can i Get the List of all Video files from Library in ios sdk
for Images
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[`allVideos` addObject:dic];
}
}];
else
{
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
--------for ALL PHOTOS
NSArray *imageArray;
NSMutableArray *mutableArray;
-(void)getAllPhotosFromCamera
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
NSLog(#"%d",(int)result.count);
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in result) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
imageArray = [images copy]; // You can direct use NSMutuable Array images
}

Tab bar image not working

I need your help here.
My app has 5 tab bars.
The first tab bar's image will be missing after make a phone call using openURL.
And this is only happen when running the app in iOS 8/9.
Below is the coding where I make a phone call:
-(void)callDistributor
{
NSString *phoneNo= [#"tel://" stringByAppendingString:phoneNumber_];
phoneNo = [phoneNo stringByReplacingOccurrencesOfString:#" " withString:#""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNo]];
}
Below is the coding (in delegate.m) where the tab bars are created:
- (void)addCustomTabbar {
NSArray *array =
[NSArray arrayWithObjects:#"products",
#"fav",
#"buy",
#"about",
#"settings", nil];
UIImage *buttonImage, *buttonImageSelected;
for (int i = 0; i < [array count]; i++) {
NSString *active =
[NSString stringWithFormat:#"%#_active.png", [array objectAtIndex:i]];
NSString *inActive =
[NSString stringWithFormat:#"%#.png", [array objectAtIndex:i]];
buttonImage = [UIImage imageNamed:inActive];
buttonImageSelected = [UIImage imageNamed:active];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = i;
button.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleTopMargin);
CGFloat heightDifference =
buttonImage.size.height -
tabBarController_.tabBar.frame.size.height;
button.frame = CGRectMake(i * buttonImage.size.width,
tabBarController_.view.frame.size.height -
tabBarController_.tabBar.frame.size.height - 1 - heightDifference,
buttonImage.size.width,
buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:buttonImageSelected
forState:UIControlStateSelected];
[button addTarget:self
action:#selector(changeTabbar:)
forControlEvents:UIControlEventTouchDown];
[button setSelected:(i == 0)];
[tabBarController_.view addSubview:button];
}
addedTabBar_ = YES;
}
- (void)changeTabbar:(id)sender {
int tagNum = [sender tag];
tabBarController_.selectedIndex = tagNum;
for (UIView *view in tabBarController_.view.subviews) {
if ([view isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)view;
[button setSelected:(tagNum == button.tag)];
}
}
}
Only the first tab bar will missing after phone call, the other 4 tab bars are working fine.
Any ideas? Thanks in advance.

how to display ad banner (buzzcity) in cocos2d project?

is there a way to put UIView by converting it to EAGLView or should i have to add CAlayer ?
whats the best way to do it?
any Example codes related to BuzzCity for Cocos2d would be nice
what i have found till now----
btnAD = [CCMenuItemImage itemFromNormalImage:#"underwater-images-paradox-visual-wallpapers-title-search-196522.jpg" selectedImage:#"underwater-images-paradox-visual-wallpapers-title-search-196522.jpg" target:self selector:#selector(AdbuttonAction)];
btnAD.position=ccp(0, 0);
what i am trying is to display ad on button image...
and call the url for ad on buttonAction
how to display this button on top of my uiview?
documentation of buzzCity ad integration
http://docs.buzzcity.net/wiki/IOS_SDK#Advanced_Integration_using_BuzzCity_iOS_SDK
you can not sandwich UIViews between two cocos nodes. If you want an ad button, display the ad as background of a UIButton, or simply make the ad "touchable" by testing if touch location is within ad's frame.
first i saved my image to documents directory
- (NSString *)saveImage {
NSURL *url = [NSURL URLWithString:#"http://ads.buzzcity.net/show.php?partnerid=8404&browser=app_apple"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//convert image into .png format.
NSData *imageData = UIImagePNGRepresentation(image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:#"myImage"];
[imageData writeToFile:fullPath atomically:YES];
NSLog(#"image saved");
return fullPath;
}
then i added that path to **itemFromNormalImage:fullPath**
NSString *fullPath=[self saveImage];
btnAD = [CCMenuItemImage itemFromNormalImage:fullPath selectedImage:fullPath target:self selector:#selector(AdButtonAction)];
NSLog(#"btnAD %#", btnAD);
CCMenu *adMenu = [CCMenu menuWithItems:btnAD, nil];
[self addChild:adMenu];
adMenu.position = ccp(350 ,size.height-50);
finally on button action open the url
-(void)AdButtonAction
{
NSURL *url = [NSURL URLWithString:#"http://click.buzzcity.net/click.php?partnerid=8404&browser=app_apple"];
NSLog(#"url = %#",url);
[[UIApplication sharedApplication] openURL:url];
}

obj-c return block NSString to c++ after request

I'm trying to get this data correctly back to c++, but there are some random crashes. I want to access the data in C++. Sometimes it does, sometime it doesn't. I couldn't find a clear example on how to return this data. Here's my code:
- (NSString*) sendRequestToServer : (CLLocationCoordinate2D) location {
NSLog(#"getting geo from server %# %# ", [NSString stringWithFormat:#"%f", location.latitude],[NSString stringWithFormat:#"%f", location.longitude]);
__block long returnBytesSend = 0;
__block long returnBytesTotal = 0;
__block NSString* tempData = #"" ;
__block BOOL foundNow = false;
self.data = nil;
for (NXOAuth2Account *account in [[NXOAuth2AccountStore sharedStore] accounts]) {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject: [NSString stringWithFormat:#"%f", location.latitude] forKey: #"latitude"];
[params setObject: [NSString stringWithFormat:#"%f", location.longitude] forKey:#"longitude" ];
[params setObject: #"10" forKey: #"radius" ];
[params setObject: #"5" forKey: #"limit"];
NXOAuth2Client *client = [account oauthClient];
NXOAuth2AccessToken *tokenData = [client accessToken];
NSString * clientAccessToken = [tokenData accessToken];
NSString * clientRefreshToken = [tokenData refreshToken];
if (clientAccessToken && clientRefreshToken ){
[NXOAuth2Request performMethod:#"GET"
onResource:[NSURL URLWithString:#"http://www.server.com/list"]
usingParameters: params
withAccount:account
sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) {
returnBytesSend = bytesSend ;
returnBytesTotal = bytesTotal;
}
responseHandler:^(NSURLResponse *response, NSData *responseData2, NSError *error){
NSLog(#"FOUND DATA");
NSRange range = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding] rangeOfString : #"facebook_id"];
if(range.location != NSNotFound) {
tempData = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding]retain];
//NSLog(#"%#", tempData);
self.data = [[tempData copy] autorelease];
foundData = true;
}
}];
}
}
return tempData;
}
I was trying to acces the data this way:
#interface oAuthView : UIWebView
#property (nonatomic, strong) __block NSString* data;
#property (nonatomic) __block BOOL foundData;
and in c++ like this:
oAuthView *getWebView;
getWebView =[[oAuthView alloc] initWithFrame:CGRectMake(10,40,300,400)];
if ([getWebView foundData] )
string dataS = string([[artPartView data] UTF8String]));

UITableView is not reloading

here is the situation:
I have a "UITableViewController" which loads objects with RestKits "RKFetchedResultsTableController". After clicking on a cell I switch to a detail UITableViewController also driven by a "RKFetchedResultsTableController" which gives me a corresponding answer text for the selected object.
The problem is now, if I go back to the first "UITableViewController" and select another object in the table the old answer text from the previous selected object is in the detail table. If I use the "pullToRefresh" function the table gets refreshed and the correct answer is loading.
Why is the old answer from the previous object still in the tableView and not the correct answer for the new selected Object even if I tell [tableController loadTable] in the viewWillAppear method.
AppDelegate:
#
interface AppDelegate ()
#property (nonatomic, strong, readwrite) RKObjectManager *objectManager;
#property (nonatomic, strong, readwrite) RKManagedObjectStore *objectStore;
#end;
#implementation AppDelegate
#synthesize window = _window, isAuthenticated;
#synthesize objectManager;
#synthesize objectStore;
- (void)initializeRestKit
{
//self.objectManager = [RKObjectManager managerWithBaseURLString:#"http://falling-ocean-1302.herokuapp.com"];
self.objectManager = [RKObjectManager managerWithBaseURLString:#"http://falling-ocean-1302.herokuapp.com"];
self.objectManager.serializationMIMEType = RKMIMETypeJSON;
self.objectManager.acceptMIMEType = RKMIMETypeJSON;
self.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:#"MMmtvzme.sqlite"];
self.objectManager.objectStore = self.objectStore;
self.objectManager.mappingProvider = [MMMappingProvider mappingProviderWithObjectStore:self.objectStore];
self.objectManager.client.cachePolicy = RKRequestCachePolicyNone;
RKLogConfigureByName("RestKit", RKLogLevelTrace);
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKLogConfigureByName("RestKit/Network/Queue", RKLogLevelTrace);
// Enable automatic network activity indicator management
objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES;
[objectManager.router routeClass:[MMRequest class] toResourcePath:#"/requests" forMethod:RKRequestMethodPOST];
[objectManager.router routeClass:[MMRequest class] toResourcePath:#"/requests" forMethod:RKRequestMethodDELETE];
[objectManager.router routeClass:[MMAnswer class] toResourcePath:#"/requests/:request_id/answers" forMethod:RKRequestMethodPOST];
}
Ok this is the code from the first UITableViewController
#interface MMMyRequestList ()
#property (nonatomic, strong) RKFetchedResultsTableController *tableController;
#end
#implementation MMMyRequestList
#synthesize tableController;
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureRKTableController];
[self configureCellMapping];
[self useCustomNib];
}
- (void)configureRKTableController{
self.tableController = [[RKObjectManager sharedManager] fetchedResultsTableControllerForTableViewController:self];
self.tableController.autoRefreshFromNetwork = YES;
self.tableController.pullToRefreshEnabled = YES;
self.tableController.resourcePath = #"/requests";
self.tableController.variableHeightRows = YES;
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"request_id" ascending:NO];
self.tableController.sortDescriptors = [NSArray arrayWithObject:descriptor];
tableController.canEditRows = YES;
}
- (void)configureCellMapping{
RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping];
cellMapping.cellClassName = #"MMRequestCell";
cellMapping.reuseIdentifier = #"MMRequest";
cellMapping.rowHeight = 100.0;
[cellMapping mapKeyPath:#"title" toAttribute:#"requestLabel.text"];
[cellMapping mapKeyPath:#"user.first_name" toAttribute:#"userLabel.text"];
cellMapping.onSelectCellForObjectAtIndexPath = ^(UITableViewCell *cell, id object, NSIndexPath* indexPath)
{
MMMyRequestListAnswer * uic = [self.storyboard instantiateViewControllerWithIdentifier:#"MMMyRequestListAnswer"];
MMRequest *request = [self.tableController objectForRowAtIndexPath:indexPath];
if ([uic respondsToSelector:#selector(setRequest:)]) {
[uic setRequest:request];
}
[self.navigationController pushViewController:uic animated:YES];
};
[tableController mapObjectsWithClass:[MMRequest class] toTableCellsWithMapping:cellMapping];
}
- (void)useCustomNib{
[self.tableView registerNib:[UINib nibWithNibName:#"MMRequestCell" bundle:nil] forCellReuseIdentifier:#"MMRequest"];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSLog(#"Hit error: %#", error);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
/**
Load the table view!
*/
[tableController loadTable];
}
After clicking on a cell the Detail UIViewController come into action
interface MMMyRequestListAnswer ()
#property (nonatomic, strong) RKFetchedResultsTableController *tableController;
#end
#implementation MMMyRequestListAnswer
#synthesize tableHeaderView, requestTextLabel;
#synthesize request;
#synthesize tableController;
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureRKTableController];
[self configureCellMapping];
[self useCustomNib];
}
- (void)configureRKTableController{
self.tableController = [[RKObjectManager sharedManager] fetchedResultsTableControllerForTableViewController:self];
self.tableController.autoRefreshFromNetwork = YES;
self.tableController.pullToRefreshEnabled = YES;
self.tableController.resourcePath = [NSString stringWithFormat:#"/requests/%i/answers", [self.request.request_id intValue]];
self.tableController.variableHeightRows = YES;
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"answer_id" ascending:NO];
self.tableController.sortDescriptors = [NSArray arrayWithObject:descriptor];
}
- (void)configureCellMapping{
RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping];
cellMapping.cellClassName = #"MMRequestAnswerCell";
cellMapping.reuseIdentifier = #"MMAnswer";
cellMapping.rowHeight = 80.0;
[cellMapping mapKeyPath:#"text" toAttribute:#"answerLabel.text"];
[cellMapping mapKeyPath:#"user.first_name" toAttribute:#"userLabel.text"];
[tableController mapObjectsWithClass:[MMAnswer class] toTableCellsWithMapping:cellMapping];
}
- (void)useCustomNib{
[self.tableView registerNib:[UINib nibWithNibName:#"MMRequestAnswerCell" bundle:nil] forCellReuseIdentifier:#"MMAnswer"];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
/**
Load the table view!
*/
[tableController loadTable];
}
The Object Mapping is handled in this Class:
#implementation MMMappingProvider
#synthesize objectStore;
+ (id)mappingProviderWithObjectStore:(RKManagedObjectStore *)objectStore {
return [[self alloc] initWithObjectStore:objectStore];
}
- (id)initWithObjectStore:(RKManagedObjectStore *)theObjectStore {
self = [super init];
if (self) {
self.objectStore = theObjectStore;
[self setObjectMapping:[self requestObjectMapping] forResourcePathPattern:#"/requests" withFetchRequestBlock:^NSFetchRequest *(NSString *resourcePath) {
NSFetchRequest *fetchRequest = [MMRequest fetchRequest];
return fetchRequest;
}];
[self setObjectMapping:[self answerObjectMapping] forResourcePathPattern:#"/requests/:request_id/answers" withFetchRequestBlock:^NSFetchRequest *(NSString *resourcePath) {
NSFetchRequest *fetchRequest = [MMAnswer fetchRequest];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"answer_id" ascending:YES]];
return fetchRequest;
}];
[self setSerializationMapping:[self.requestObjectMapping inverseMapping] forClass:[MMRequest class]];
[self setSerializationMapping:[self.answerObjectMapping inverseMapping] forClass:[MMAnswer class]];
[self setSerializationMapping:[self.userObjectMapping inverseMapping] forClass:[MMUser class]];
}
return self;
}
- (RKManagedObjectMapping *)userObjectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntityWithName:#"MMUser" inManagedObjectStore:self.objectStore];
mapping.primaryKeyAttribute = #"user_id";
[mapping mapAttributes:#"first_name", nil];
[mapping mapKeyPathsToAttributes:
#"id", #"user_id",
nil];
return mapping;
}
- (RKManagedObjectMapping *)answerObjectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntityWithName:#"MMAnswer" inManagedObjectStore:self.objectStore];
mapping.primaryKeyAttribute = #"answer_id";
[mapping mapAttributes:#"text",#"request_id",#"user_id", nil];
[mapping mapKeyPathsToAttributes:
#"id", #"answer_id",
nil];
[mapping mapKeyPath:#"user" toRelationship:#"user" withMapping:[self userObjectMapping]];
[mapping mapKeyPath:#"request" toRelationship:#"request" withMapping:[self requestObjectMapping]];
return mapping;
}
- (RKManagedObjectMapping *)requestObjectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntityWithName:#"MMRequest" inManagedObjectStore:self.objectStore];
mapping.primaryKeyAttribute = #"request_id";
[mapping mapAttributes:#"title",#"user_id", nil];
[mapping mapKeyPathsToAttributes:
#"id", #"request_id",
nil];
[mapping mapKeyPath:#"user" toRelationship:#"user" withMapping:[self userObjectMapping]];
return mapping;
}
OK Figured it out!!! Some digging revealed that I was loading my UITableviewcontroller BEFORE the mapping provider.
The fix was, to take [self initialiserestkit] method in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
and put it before any of the code in this method (i.e. make [self initialiserestkit] the first line of the didfinishlaunchingwithoptions method.
Issue solved. Now the tableview is loaded AFTER the mappings so everything works as it should.