UITableView update data on row selection - ios

I have a UITableView that get its data from an array and the array contains the filenames of a directory.
I am trying to make user edit filename on row selection.
My code is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self editChattWithName:[self.listArray objectAtIndex:indexPath.row] atIndex:indexPath];
[self.tabView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)editChattWithName:(NSString*)name atIndex:(NSIndexPath *)indexPath {
UIAlertView* editAlert = [[UIAlertView alloc]
initWithTitle:nil
message:#"Edit FileName"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Update", nil];
[editAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField* nameField = [editAlert textFieldAtIndex:0];
[nameField setPlaceholder:#"New FileName"];
[nameField setText:name];
[editAlert show];
[editAlert release];
NSString *newFileName = nameField.text;
[editAlert showWithCompletion:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == 0) { }
else if (buttonIndex == 1) {
NSError *error;
// Edit filename inside directory
[fm moveItemAtPath:[NSString stringWithFormat:#"%#%#",directory,name] toPath:[NSString stringWithFormat:#"%#%#",directory,newFileName] error:&error];
// Update value inside array
[self.listArray replaceObjectAtIndex:indexPath.row withObject:newChatName];
// reload table data to show new filename
[self.tabView reloadData];
NSLog(#"Old Filename: %#%#",directory,name);
NSLog(#"New Filename: %#%#",directory,newFileName);
NSLog(#"Error: %#",error);
}
}];
}
The issue is that name and newFileName are having the same value name and that is resulting an error with NSFileManager saying that the file already exists.
I have tried removing [nameField setText:name] but the problem was still there.
I am out of luck and not able to find the issue, your help is much appreciated.

Well, if you already know that the method moveItemAtPath:toPath: is causing the error only in case that the old and the new file name are identical then it should be quite easy to catch this error:
if (![newFileName isEqualToString:name]) {
[fm moveItemAtPath:[NSString stringWithFormat:#"%#%#",directory,name] toPath:[NSString stringWithFormat:#"%#%#",directory,newFileName] error:&error];
}
Now your file will only me moved (i.e. renamed) when the new file name differs from the old name.
Edit:
Furthermore, if you want to get the new file name that the user just entered in the alert view you should put this line:
NSString *newFileName = nameField.text;
in your completion block. Otherwise it will be set when the alert view is first displayed and hence have its initial value. To put it all together:
[editAlert showWithCompletion:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == 1) {
NSString *newFileName = nameField.text;
NSError *error;
// Edit filename inside directory
if (![newFileName isEqualToString:name]) {
[fm moveItemAtPath:[NSString stringWithFormat:#"%#%#",directory,name] toPath:[NSString stringWithFormat:#"%#%#",directory,newFileName] error:&error];
}
// Update value inside array
[self.listArray replaceObjectAtIndex:indexPath.row withObject:newChatName];
// reload table data to show new filename
[self.tabView reloadData];
}
}];
Supplement:
In order to not confuse other users it should be noted that showWithCompletion: is not a native UIAlertView method. An Objective-C category has been created to extend UIAlertView with this method. An example can be found here.

Related

UITableview not loaded data on 3rd time?

Don't know what to do with it. but i loaded data and load table when data is loaded,
[manager POST:path parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
arryGlobal = [NSMutableArray new];
[arryGlobal addObject:responseObject];
if([[[[arryGlobal valueForKey:#"Success"] objectAtIndex:0] stringValue] isEqualToString:#"1"]){
arryGlobal = [[arryGlobal valueForKey:#"Result"] objectAtIndex:0];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tblMainCategory reloadData];
});
}
else if([[[[arryGlobal valueForKey:#"Success"] objectAtIndex:0] stringValue] isEqualToString:#"0"]){
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//here is place for code executed in error case
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"Error: %#", [error localizedDescription]);
}];
It works perfectly two times, but when i go for 3rd time call this webservice it load data, get data, table successfully reloaded, but it not change content in table, it appear as it is in 2nd time.
SO what happens there ?? When I scroll table, then in cellForRowAtIndexPath array that i use to pass in table is contain data of 2nd time called Webservice.
EDIT:
i added this table view VievController in other view like :
MainCategory *objMain = [[MainCategory alloc] initWithNibName:#"MainCategory" bundle:nil];
[objMain LoadData:tag];
objMain.view.frame = CGRectMake(0, 0, self.bgViewCat.frame.size.width, self.bgViewCat.frame.size.height);
[self.bgViewCat insertSubview:objMain.view atIndex:1];
[self addChildViewController:objMain];
[objMain didMoveToParentViewController:self];
Try This
if([[[[arryGlobal valueForKey:#"Success"] objectAtIndex:0] stringValue] isEqualToString:#"1"])
{
[arryGlobal removeAllObjects];
arryGlobal=[NSarray alloc]init];
arryGlobal = [[arryGlobal valueForKey:#"Result"] objectAtIndex:0];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tblMainCategory reloadData];
});
}
the block:success() already run in main queue;you needn't use dispatch_async(dispatch_get_main_queue();
and arryGlobal is a kind of NSMutableArray;why you use the function called "thevalueforKey:" to get the value ?
I think maybe you should print the responseObject to check your data
ok so ther's error on :
[self.bgViewCat insertSubview:objMain.view atIndex:1];
Instead of this I use this and everything is fine, don't know why?:
[self.bgViewCat addSubview:objMain.view];

get share link (file link) for BOX in iOS

I am using box SDK V2 and the folder picker present in the sample app. I do not need any upload or download facility. I just need to get the file's ShareLink.
I am successfully displaying the filename and everything but not the share link.
I am getting a NULL.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BoxItem *item = (BoxItem *)[self.folderItemsArray objectAtIndex:[indexPath row]];
NSLog(#"item type : %# : %# : %# ", item.type, item.name, item.sharedLink);
}
Am using this code.(from sample app)
I am getting results like:
1.item type : file : dummy.pdf : (null)
2. item type : file : presentations-tips.ppt : (null)
I am not getting the sharedlink.
first reaction: may be sharedlinks are not created for those files, So:
I went to my box account and created share links for those files through my desktop.
and rechecked. but got same result.
I need the shared link badly. Please help. Thanks in advance
I got the solution for getting shared link of file. Write following lines of code where you want to get shared link.
BoxFileBlock successfulShare = ^(BoxFile *file)
{
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"File Share Successful" message:[NSString stringWithFormat:#"Shared link: %#", [file.sharedLink objectForKey:#"url"]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
});
};
BoxAPIJSONFailureBlock failedShare = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
BOXLog(#"status code: %i", response.statusCode);
BOXLog(#"share response JSON: %#", JSONDictionary);
};
BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
BoxSharedObjectBuilder *sharedBuilder = [[BoxSharedObjectBuilder alloc] init];
sharedBuilder.access = BoxAPISharedObjectAccessOpen;
builder.sharedLink = sharedBuilder;
[[BoxSDK sharedSDK].filesManager editFileWithID:YOUR_FILE.modelID requestBuilder:builder success:successfulShare failure:failedShare];

iOS - twitter two-part post

I have my app filling out the tweet sheet for the user and sometimes it may go over 140 characters including the url. I am trying to develop a method which can split the tweet into two parts and post part 2 first, and then part 1 so it will look like:
(1/2) blah blah blah
(2/2) blah blah blah
Here is the method I have so far:
(void)sendTweet:(NSString *)msg setURL:(NSString*)url setImg:(UIImage*)img {
// Set up the built-in twitter composition view controller.
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
// Set the initial tweet text. See the framework for additional properties that can be set.
if (![tweetViewController addURL:[NSURL URLWithString:url]])
NSLog(#"Unable to add the URL!");
if (![tweetViewController addImage:img])
NSLog(#"Unable to add the image!");
if (![tweetViewController setInitialText:msg])
NSLog(#"Unable to add the message!");
// Create the completion handler block.
[tweetViewController setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
NSString *output;
switch (result) {
case TWTweetComposeViewControllerResultCancelled:
// The cancel button was tapped.
output = #"Tweet cancelled.";
break;
case TWTweetComposeViewControllerResultDone:
// The tweet was sent.
output = #"Tweet sent.";
break;
default:
break;
}
// Show alert to see how things went...
UIAlertView* alertView = [[UIAlertView alloc]
initWithTitle:#"The Predictor"
message:output
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
// Dismiss the tweet composition view controller.
[self dismissModalViewControllerAnimated:YES];
}];
// Present the tweet composition view controller modally.
[self presentModalViewController:tweetViewController animated:YES];
}
Here is how i'm calling it, although the two part stuff isn't working...and I would like this functionality built-in to the method above.
if ([alertView tag] == 1) {
if (buttonIndex != [alertView cancelButtonIndex]) {
NSString *theURL = #"PredictorApps.com";
NSString *theTweet = [NSString stringWithFormat:#"%# - %#\n%#", [[Singleton sharedSingleton].spreadDate substringToIndex:5], theTitle, theMessage];
if (([theURL length] + [theTweet length]) <= 120)
[self sendTweet:theTweet setURL:theURL setImg:nil];
else if (([theURL length] + [theTweet length]) > 120) {
NSString *partTwo = [theTweet substringFromIndex:(([theURL length] + [theTweet length]) / 2)];
NSLog(#"Part Two: %#", partTwo);
[self sendTweet:partTwo setURL:theURL setImg:nil];
NSString *partOne = [theTweet substringToIndex:(([theURL length] + [theTweet length]) / 2)];
NSLog(#"Part One: %#", partOne);
[self sendTweet:partOne setURL:theURL setImg:nil];
}
}
}
any assistance is appreciated.
You have to use URL shorteners for reduce the URL size to post in twitter of facebook...For that you can refer to this link..This is a simple coding to shortening any type of URL u have..So u can reduce 2 part of post into single..I hope this will help you....
http://www.icodeblog.com/2010/02/04/iphone-coding-recipe-shortening-urls/
All the best....

UITableView didSelectRowAtIndexPath error - when selecting item again

Loaded a list of items on to the UITableview and was able to click and show an alert for the row selected . But however after saying "ok" on the alert and i reclick on the already selected row my code breaks down saying "Thread 1:Program received signal:EXC_BAD_ACCESS".please take a look at the code below.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *playerselected = [exercises objectAtIndex:indexPath.row];
NSString *video = [playerselected valueForKey:#"video"];
NSString *msg = [[NSString alloc] initWithFormat:#"You have selected %#", video];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Player selected"
message:msg
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[video release];
[msg release];
}
PLease suggest me what could be the issue here.
Don't release video.
When you retrieve a value from an NSDictionary you don't own it unless you explicitly retain it.
To be more specific, when you retrieve your string it is still owned by the dictionary. When you release it, you are releasing an object that you do not own, resulting in it being over-released. As a result it is deallocated, and when you next try to access it the memory is no longer valid and your app crashes.

Display a loading indicator after user taps "Share" and before request is completed?

The issue I have is that after users tap on the "Share" button of the FBDialog, they do not get any visual feedback until the request completes or fail... and over 3G that can takes a while. During this time users do not know if they tapped "Share" correctly or not, and there's risk of posting content twice.
Is there a way I can get a callback so I can display a loading indicator during this time? Where should I put this piece in?
Thank you!
Below code you write to fbAgent.m and also obser code here u get one "PID" at that time u write to alert msg ....... user can understand to that msg was success posted Facebook.
I hope this helps.
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
// Calling the delegate callback
[delegate facebookAgent:self didLoadName:name];
} else if ([request.method isEqualToString:#"facebook.users.setStatus"]) {
newStatus = nil;
NSString* success = result;
if ([success isEqualToString:#"1"]) {
// Calling the delegate callback
[delegate facebookAgent:self statusChanged:YES];
} else {
[delegate facebookAgent:self statusChanged:NO];
}
} else if ([request.method isEqualToString:#"facebook.photos.upload"]) {
NSDictionary* photoInfo = result;
NSString* pid = [photoInfo objectForKey:#"pid"];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:#"success Uploaded Your image please check your FaceBook", pid] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alertView show];
[alertView release];
fbbut.enabled=YES;
[fbact stopAnimating];
self.uploadImageData = nil;
self.uploadImageCaption = nil;
self.uploadImageAlbum = nil;
//[delegate facebookAgent:self photoUploaded:pid];
if(newStatus){
[self setStatus:newStatus];
}
}
}
Start your indicator when you click on button and stop on Delegate of Facebook function
- (void)dialogDidComplete:(FBDialog *)dialog
Hope it helps....

Resources