ASIHTTPRequest UIProgressView don´t work - ios

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

Related

Tabbed bar application buttons blocked when NSUrlSendAssynchronousrequest operation running

I have a tabbed bar application in which one of the buttons loads the content of a webpage to a UIWebView.
The problem I am facing is that while the connection attempting to fetch the data the tab bar buttons are non responsive until either the page is done loading or connection has failed.
Is there a better way to perform this operation so the user can switch out of that tab if he/she changes their mind for example.
Thanks and here is the code:
- (void)loadThrillsSite
{
[self.webView setDelegate:self];
NSString *urlString = #"https://www.Thrills.in";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil) [self.webView loadRequest:request];
else if (error != nil) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Connection Error!" message:#"Failed to connect to server\nPlease check your internet connection and try again" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
[hudImageView removeFromSuperview];
[self.spinner stopAnimating];
[patternView removeFromSuperview];
}
UIWebView's loadRequest method description:
Connects to a given URL by initiating an asynchronous client request.
It already makes a asynchronous call so you do not need to use another block. Just call [self.webView loadRequest:request]; You can handle errors on - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error method.
Other notes: Your url is not working right now and do not do any UI related work like showing an alert view on background thread. Hope it helps.
- (void)loadThrillsSite
{
[self.webView setDelegate:self];
NSString *urlString = #"https://www.Thrills.in";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
[hudImageView removeFromSuperview];
[self.spinner stopAnimating];
[patternView removeFromSuperview];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Connection Error!" message:#"Failed to connect to server\nPlease check your internet connection and try again" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}

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];
}

Download option on long press of UITableViewCell

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.

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