Download option on long press of UITableViewCell - ios

I have a UITableView that is populated with an array, it contains cell label and cell detail text, the detail text is basically the URL at which the file is saved. I want that on long press of the uitableviewcell a pop up comes up which has the option to download the file and on clicking that option the file is saved in a specific directory on the phone memory.
How can i do that?

Add gesture to your cell object
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0; //seconds
lpgr.delegate = self;
[objMyTableViewCell addGestureRecognizer:lpgr];
[lpgr release];
Handle it
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
UITableVIewCell *objTableCell = (UITableVIewCell*)gestureRecognizer
NSURL *url = [NSURL URLWithString:objTableCell.lable.text];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[request setDownloadDestinationPath:[NSString stringWithFormat:#"%#",filePath]]; //use the path from earlier
[queue addOperation:request]; //queue is an NSOperationQueue
[request setDownloadProgressDelegate:self];
[request setShowAccurateProgress:YES];
}
Response method for download file
- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"hurreh!!"
message: #"Your download complete"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
//Do something useful with the content of that request.
}
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}

For long press on the UITableViewCell you can use the UILongPressGestureRecognizer.
To show the options you can use the UIActionSheet.
To download file you can use NSURLConnection or ASIHTTPRequest.

Related

how to set button enable and disbale in ios app?

i am creating 2 buttons one for like and one for dislike when i click like button its disable and also disable dislike button same time.and so on. and its not change when i am run the application second time. i am implemented for that its work but problem is that when i run my application second time once again that button enable. problem is that i don't want that button same button enable.please help me what is the problem in my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:102/255.0
green:102/255.0 blue:204/255.0 alpha:1.0];
self.navigationController.navigationBar.titleTextAttributes =
#{NSForegroundColorAttributeName : [UIColor whiteColor]};
smsdisplaytext.editable=NO;
smsdisplaytext.backgroundColor= [UIColor colorWithRed:102/255.0 green:102/255.0
blue:204/255.0 alpha:1.0];
self.navigationItem.title=#"Insta SMS";
[ self getSmsData];
[self smsdisplay];
[self getLike];
}
-(void)sendlike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request setPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setTag:2];
[request setPostValue:#"true" forKey:#"like"];
[request setDelegate:self];
[request startAsynchronous];
}
-(void)senddislike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request s etPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setPostValue:#"false" forKey:#"Like"];
[request setTag:3];
[request setDelegate:self];
[request startAsynchronous];
}
- (void) requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
responseString = [request responseString];
NSLog(#"%#",responseString);
if(request.tag==1)
{
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSArray *jsondata = [parser objectWithString:responseString];
NSLog(#"%#",jsondata);
for (NSObject* item in jsondata)
{
likelabel.text = [[item valueForKey:#"Liked"] stringValue];
dislikelabel.text = [[item valueForKey:#"Disliked"] stringValue];
}
}
else if(request.tag==2)
{
[self getLike];
}
/////// getting comment
else if(request.tag==4)
{
// get comments
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSMutableArray *jsondata = [parser objectWithString:responseString];
for(int i=0;i<jsondata.count;i++)
{
NSObject *temp = [jsondata objectAtIndex:i];
NSMutableDictionary *message = [[NSMutableDictionary alloc] init];
message[kMessageContent]=[temp valueForKey:#"Comment"];
message[#"Timestamp"]=[self dateWithJSONString:[temp valueForKey:#"CreatedDate"]];
last=[[temp valueForKey:#"Id"] integerValue];
[_chatController addNewMessage:message];
}
}
else
{
////post comment
[self getComment];
}
}
//this method for getting like and dislike
-(void)getLike
{
NSString *url = [NSString
stringWithFormat:#"http://sms.instatalkcommunications.com/apireq/GetRatingsForSMS?
t=1&h=admin&cid=%#&token=1234567890&email=test#test.com",self.Id];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:#"GET"];
[request setTag:1];
[request setDelegate:self];
[request startAsynchronous];
}
// here for like button
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
UIButton *btnlike = (UIButton *) sender;
btnlike.enabled = NO;
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
}
//here i am action for dislike button
- (IBAction)btndislike:(id)sender
{
NSLog(#"keypress");
[self senddislike];
[self getLike];
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
_btnlike.enabled = NO;
}
#end
As I'm not an native english speaker, I hope I've understood correctly what you are trying to achieve.
If I understand correctly, You have a 'Like' and 'Dislike' buttons, and when the user presses on one of them, you want both to be disabled,
Which is working correctly for the current run.
But, if I understand correctly, the next time the app runs, the buttons are 'reset' to be enabled, and you don't want that,
You want the button be disabled every time the app runs.
If I did understood you correctly, the way to 'save' state of objects is using the NSUserDefaults.
You might have a better way to implement it than my example below, but it should do the trick, and also give you a better understanding on how to implement it, incase you need to modify my code.
Add the following method:
-(void)disableButtons {
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: #"buttonsDisabled"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
now, at the end of the 'Like' and 'Dislike' buttons, just call the following methods by adding to your code:
[self disableButtons]
Now, add the following to viewDidLoad:
// someplace in viewDidLoad
BOOL bottunsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey: #"buttonsDisabled"];
if(buttonsDisabled) {
self.btndislike.enabled = NO;
self.btnlike.enabled = NO;
}
The buttons defaults state are enabled, so the above code will change them, incase they have been disabled in previous runs.
Note that I also assumed you have a reference to the buttons (I assume you've created them in interface builder), if not, just create a property/ivar that will hold a reference to them.
And as Ian MacDonald mentioned above, in the 'Like' button method, you are disabling only the 'Like' button twice, and not disabling the 'Dislike' button.
In order to fix it, change the code to the following (again, I assume you have some sort of reference to both of them):
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
self.btnlike.enabled = NO;
self.btndislike.enabled = NO;
[self disableButtons];
}
As I've said above, I'm not an native english speaker,
So I hope my answer was clear enough.
If something isn't clear, just tell me and I'll try to rephrase it.
Good luck mate!

How to show loading view controller in my webservices

I want to show a loading view controller or activity indicator view when I call my loginUserintoserver method but while debugging I found the view becomes inactive at this line.
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
For sometime till I get the response. I have tried showing activity indicators but did not succeed. Please any guidelines to resolve this. Thanks in advance.
-(void) loginUserintoserver
{
NSString *str_validateURL = #"callogin";
// em,password,devicereg,devicetype,flag = ("e" or "m")
NSString *str_completeURL = [NSString stringWithFormat:#"%#%#", str_global_domain, str_validateURL];
NSURL *url = [NSURL URLWithString:str_completeURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
str_global_UserPhone = [NSString stringWithFormat:#"%#%#",signupCountryCodeTextField.text,signupMobileTextField.text];
NSString *postData = [NSString stringWithFormat:#"em=%#&password=%#&devicereg=%#&devicetype=%#&flag=%#", loginEmailTextField.text, loginPasswordTextField.text, str_global_DeviceRegID, #"1", [NSString stringWithFormat:#"%#", emailphoneFlag]];
NSLog(#"==============%#",postData);
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
// here the view becomes inactive and takes time to get response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSLog(#"response data is %#", responseData);
if (responseData == nil)
{
NSLog(#"No data from server");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No data downloaded from server!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
}
else
{
NSLog(#"response data is %#", responseData);
NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"returnString....%#",returnString);
NSDictionary *response_dic = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSString *msg;
msg = [response_dic objectForKey:#"Result"];
NSDictionary *loginDict=[[NSDictionary alloc]init];
loginDict=[response_dic objectForKey:#"Result"];
NSLog(#"msg is : %# ",[response_dic objectForKey:#"Result"]);
if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"0"])
{
// success
NSLog(#"Successfull Login!!!!!");
NSString *UserId=[loginDict objectForKey:#"userid"];
[[NSUserDefaults standardUserDefaults] setValue:UserId forKey:#"LoginId"];
[self initRevealViewController];
} else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"1"]){
NSLog(#"Invalid Password!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"ReEnter Password" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"3"]){
NSLog(#"Invalid input parameters!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"Email address or Mobile number, Password, devicereg, devicetype, flag are Mandatory" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}else if ([[[response_dic objectForKey:#"Result"] objectForKey:#"ErrorCode"] isEqualToString:#"6"]){
NSLog(#"Invalid input parameters!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"User Registered but not activated" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
You have to used this: MBProgressHUD
Import framwork from above link and do some stuff like:
.h file:
#import "MBProgressHUD.h"
MBProgressHUD *HUD;
.m file do this :
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
[HUD show:YES];
// call your webservice here
[HUD hide:YES];
May be it will help.
Happy coding...:)
Mak ,
I use MBProgressHUD all my project . You can use also .Really MBProgressHUD is suitable , lightweight.
Showing indicator :
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
hiding :
[MBProgressHUD hideHUDForView:self.view animated:YES];
Most of the answers are partial which do not point out the main issue in your code.
Synchronous request on main thread will block it, thus you cannot show any UI updates like activity indicator while the sync request is in progress. Instead make asynchronous request (or make request in background using GCD) and use UIActivityIndicatorView or any other open source available for this.
Follow this Q&A to learn how to make asyn request using GCD: NSURLConnection and grand central dispatch
You can create and add an activity indicator to the view. Present and start showing activity when request is initiated and stop the activity when request completes downloading.
Hope that helps!
https://github.com/jdg/MBProgressHUD
Download the project for MBProgressHUD , and copy MBProgressHUD.h & .m classes in to your project, Now by simply creating an instance of MBProgressHUD and using the available methods by MBProgressHUD you can show loading view on to your web services
HUD = [[MBProgressHUD alloc] initWithWindow:[[UIApplication sharedApplication] delegate].window];
[HUD showWhileExecuting:#selector(loginUserintoserver) onTarget:self withObject:nil animated:YES];
[[[UIApplication sharedApplication] delegate].window addSubview:HUD];
Hope it will help you .

How to post images to server using ASIFormDataRequest?

How to upload a image to server using ASIFormDataRequest ?
i tried to upload a image its does't show's any error while inserting. and in my requesting did finished method iam getting response as success. so what is the problem is, when i get the data what i have inserted in that i am not able to get the image what i have inserted but iam getting the image path also.
here is my code
NSString *globalurl =[[NSUserDefaults standardUserDefaults]valueForKey:#"Global_Url"];
NSString *urlStr=[NSString stringWithFormat:#"%#/InsertUserInfo?User_Name=%#&User_Pwd=%#&User_FName=%#&User_LName=%#&User_Mail=%#&User_Phno=%#&User_Address=%#&User_Dob=%#&Ic_No=%#&User_Active=%#&User_Questions=%#&User_Ans=%#",globalurl,usernameTxtFld.text,pwdTxtFld.text,firstName.text,lastName.text,email.text,phonNO.text,address.text,dateOfbirth.text,nricNo.text,#"10001",#"",#""];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request addData:dataImage withFileName:#"Image.png" andContentType:#"image/png" forKey:#"photo"];
//check if passedData is nil
if (dataImage == nil)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"title:iDnil" message:#"nil" delegate:nil cancelButtonTitle:#"fgff" otherButtonTitles:#"erer", nil];
[alert show];
}
[request startAsynchronous];
-(void)requestFinished:(ASIHTTPRequest *)request {
NSString *receivedString = [request responseString];
NSLog(#"received messge %#",receivedString);
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:receivedString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
NSLog(#"dict is %#",info);
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissModalViewControllerAnimated:YES];
}
You can use
[request setFile:#"YOUR IMAGE FILE PATH" forKey:#"photo"];
instead of [request addData:dataImage withFileName:#"Image.png" andContentType:#"image/png" forKey:#"photo"];
as explained in the post . It worked for me like a charm :-)
I have uploaded an example application performing textfile, Image, Video, Images upload in queue, Videos to GitHub on this link. You may well consider having a look at it.
ASI-http-request has an optimisation option to stream your image files right away from your disk, which is the best I've seen with this library. Please consider using the below code snippet for creating ASIFormDataRequest.
// Initilize Variables
NSURL * url = [NSURL URLWithString:IMAGE_POST_URL];
// Add Image
NSString *path = [[NSBundle mainBundle]pathForResource:#"image1" ofType:#"jpg"];
// Get Image
NSData *imageData = [[NSData alloc]
initWithContentsOfFile:path];
// Return if there is no image
if(imageData != nil){
//Request-1
ASIFormDataRequest * request1;
[request1 setTag:201];
request1 = [[ASIFormDataRequest alloc] initWithURL:url];
[request1 setPostValue:#"ID = 201" forKey:#"image_upload"];
[request1 setFile:path forKey:#"image1_file"];
[request1 setDelegate:self];
[request1 setDidFinishSelector:#selector(imageUploadDidFinish:)];
[request1 setDidFailSelector:#selector(imageUploadDidFail:)];
[request1 setTimeOutSeconds:500];
[request1 setShouldStreamPostDataFromDisk:YES];
}

ASIHTTPRequest UIProgressView don´t work

I´m new in Xcode and have a problem with UIProgressView.
I found some code but I don't understand it well. Could you please explain me why UIProgressView is not closing after finish?
- (IBAction)Download:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://db.tt/5WP2pia"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
progressView = [[UIProgressView alloc]
initWithFrame:CGRectMake(30.0f, 80.0f, 225.0f, 90.0f)];
UIAlertView *progressAlert =
[[UIAlertView alloc] initWithTitle: #"Download..."
message: #"Please wait..."
delegate: self
cancelButtonTitle: nil
otherButtonTitles: nil];
[progressAlert addSubview:progressView];
[progressView setProgressViewStyle: UIProgressViewStyleBar];
[request setDownloadDestinationPath:#"/var/root/osk.rar"];
[request setDownloadProgressDelegate:progressView];
[progressAlert show];
[progressAlert release];
}
You have to manually close the alert, after ASIHTTPRequest is done. progressView != progressAlert
Don't use ASIHTTPRequest

asihttprequest Image download

Hello good morning everyone. I am using asihttprequest for a series of images download - 4 images from server.However i noticed an issues and cannot find a solution. Suppose i am downloading 4 images via URL and in case any one or 2 of the images is not available it cancels the whole queue.
Here is my code :
[networkQueue setDownloadProgressDelegate:progressIndicator];
[networkQueue setRequestDidFinishSelector:#selector(imageFetchComplete:)];
[networkQueue setRequestDidFailSelector:#selector(imageFetchFailed:)];
request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:#"http://imagees/image1.jpg"]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"1.png"]];
[request setDownloadProgressDelegate:imageProgressIndicator1];
[request setUserInfo:[NSDictionary dictionaryWithObject:#"request1" forKey:#"name"]];
[networkQueue addOperation:request];
request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:#"sdvdsvsadvsadv"]] autorelease];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"2.png"]];
[request setDownloadProgressDelegate:imageProgressIndicator2];
[request setUserInfo:[NSDictionary dictionaryWithObject:#"request2" forKey:#"name"]];
[networkQueue addOperation:request];
- (void)imageFetchComplete:(ASIHTTPRequest *)request
{
UIImage *img = [UIImage imageWithContentsOfFile:[request downloadDestinationPath]];
if (img) {
if ([imageView1 image]) {
if ([imageView2 image]) {
[imageView3 setImage:img];
} else {
[imageView2 setImage:img];
}
} else {
[imageView1 setImage:img];
}
}
}
- (void)imageFetchFailed:(ASIHTTPRequest *)request
{
if (!failed) {
if ([[request error] domain] != NetworkRequestErrorDomain || [[request error] code] != ASIRequestCancelledErrorType) {
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Download failed" message:#"Failed to download images" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
failed = YES;
}
}
The problem is that suppose fetching second image failed, it displays the error message and stops the whole operation, although image 1 is a valid image file.
Any help will be greatly appreciated.
:)
From the ASIHTTPRequest documentation:
When a request in an ASINetworkQueue fails, the queue will by default
cancel all other requests. You can disable this behaviour with [queue
setShouldCancelAllRequestsOnFailure:NO].

Resources