I need to download large file (i.e. > 40MB) to my application from server, this file will be ZIP or PDF. I achieved it using NSURLConnection, that works well if the file is smaller other wise it download a part of the fill and the execution has stopped. for example I tried to download 36MB PDF file, but but 16MB only downloaded. pls help me to know the reason? how to fix it?
FYI:
Implementation File
#import "ZipHandlerV1ViewController.h"
#implementation ZipHandlerV1ViewController
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
[mainView setBackgroundColor:[UIColor darkGrayColor]];
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadButton setFrame:CGRectMake(50, 50, 150, 50)];
[downloadButton setTitle:#"Download File" forState:UIControlStateNormal];
[downloadButton addTarget:self action:#selector(downloadFileFromURL:) forControlEvents:UIControlEventTouchUpInside];
[mainView addSubview:downloadButton];
[self setRequestURL:#"http://www.mobileveda.com/r_d/mcps/optimized_av_allpdf.pdf"];
[self.view addSubview:mainView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) setRequestURL:(NSString*) requestURL {
url = requestURL;
}
-(void) downloadFileFromURL:(id) sender {
NSURL *reqURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:reqURL];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error !" message:#"Error has occured, please verify internet connection" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error !" message:#"Error has occured, please verify internet connection.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
#end
Header File:
#import <UIKit/UIKit.h>
#interface ZipHandlerV1ViewController : UIViewController {
NSMutableData *webData;
NSString *url;
}
-(void) setRequestURL:(NSString*) requestURL;
#end
Thank you,
Updated:
This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine.
So, if you having problem like partial download, don't only stick with the code, check the server too
You are currently keeping all downloaded data in a NSMutableData object which is kept within the RAM of your device. That will, depending on the device and the available memory, at some point trigger a memory warning or even a crash.
To get such large downloads to work, you will have to write all downloaded data directly to the filesystem.
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//try to access that local file for writing to it...
NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
//did we succeed in opening the existing file?
if (!hFile)
{ //nope->create that file!
[[NSFileManager defaultManager] createFileAtPath:self.localPath contents:nil attributes:nil];
//try to open it again...
hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
}
//did we finally get an accessable file?
if (!hFile)
{ //nope->bomb out!
NSLog("could not write to file %#", self.localPath);
return;
}
//we never know - hence we better catch possible exceptions!
#try
{
//seek to the end of the file
[hFile seekToEndOfFile];
//finally write our data to it
[hFile writeData:data];
}
#catch (NSException * e)
{
NSLog("exception when writing to file %#", self.localPath);
result = NO;
}
[hFile closeFile];
}
I had the same problem, and seems that I discovered some solution.
In your header file declare:
NSMutableData *webData;
NSFileHandle *handleFile;
In your .m file on downloadFileFromURL when you get the connection initiate the NSFileHandle:
if (theConnection) {
webData = [[NSMutableData data] retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
handleFile = [[NSFileHandle fileHandleForWritingAtPath:filePath] retain];
}
then in didReceiveData instead of appending data to memory write it to disk, like this:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
if( webData.length > SOME_FILE_SIZE_IN_BYTES && handleFile!=nil) {
[handleFile writeData:recievedData];
[webData release];
webData =[[NSMutableData alloc] initWithLength:0];
}
}
when the download finish on connectionDidFinishLoading add this lines to write the file and to release connection:
[handleFile writeData:webData];
[webData release];
[theConnection release];
I'm trying it right now, hope it works..
This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine.
So, if you having problem like partial download, don't only stick with the code, check the server too.
If you're willing to use asi-http-request, it's much, much easier.
Check out https://github.com/steipete/PSPDFKit-Demo for a working example with asi.
It's about as easy as this:
// create request
ASIHTTPRequest *pdfRequest = [ASIHTTPRequest requestWithURL:self.url];
[pdfRequest setAllowResumeForFileDownloads:YES];
[pdfRequest setNumberOfTimesToRetryOnTimeout:0];
[pdfRequest setTimeOutSeconds:20.0];
[pdfRequest setShouldContinueWhenAppEntersBackground:YES];
[pdfRequest setShowAccurateProgress:YES];
[pdfRequest setDownloadDestinationPath:destPath];
[pdfRequest setCompletionBlock:^(void) {
PSELog(#"Download finished: %#", self.url);
// cruel way to update
[XAppDelegate updateFolders];
}];
[pdfRequest setFailedBlock:^(void) {
PSELog(#"Download failed: %#. reason:%#", self.url, [pdfRequest.error localizedDescription]);
}];
Related
I am facing connection lost issue while using NSURLConnection. I am using NSURLConnection for asynch download. I am downloading big file of size around 80MB. I am writing received data in file every time with proper file handling. After sometime I am getting error of connection "Connection Lost" in method of NSURLConnection delegate named didFailWithError. If I execute in simulator on Mac then it will take long time but file gets downloaded successfully without having Connection Lost error. Any suggestion how to avoid this error? or what is the reason behind this error?
Let me know if any detail is required. Please note that I have read similar kind of post but it didnt help me.
Find below code snippet and let me know if more information is required:
-(void) startDownloadFromURL:(NSString*)URLString
{
if(URLString == nil)
{
[delegate DownloadFailed:-1];
return;
}
//self.pstrBaseFilePath = filePath;
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest* pRequest = [[NSMutableURLRequest alloc] init];
[pRequest setURL:[NSURL URLWithString:URLString]];
if(gpUserDataManager.pstrSessionID == nil)
return;
[pRequest addValue:[#"ASessionID=" stringByAppendingString:gpUserDataManager.pstrSessionID] forHTTPHeaderField:#"Cookie"];
[pRequest setHTTPMethod:#"GET"];
[pRequest setTimeoutInterval:180];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:pRequest delegate:self];
[urlConnection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if([httpResponse statusCode] == 200)
{
}
else
{
//Start.NOODLE-13304
/* NSInteger iResponseCode = [httpResponse statusCode];
NSString* pstrStr = [NSString stringWithFormat:#"%d", iResponseCode];
//pTheConnection = nil;
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Response Error", #"")
message:pstrStr
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", #"")
otherButtonTitles:nil] show];
*/
[AUserDataManager ProcessResponseCode:httpResponse.statusCode];
[self.urlConnection cancel];
[delegate DownloadFailed:httpResponse.statusCode];
//End.NOODLE-13304
}
//[self.pRecvdata setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if(self.recvdData == nil)
{
self.recvdData = [[NSMutableData alloc] init];
}
[self.recvdData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// bIsResponseOK = FALSE;
//
// [NSThread detachNewThreadSelector: #selector(SpinEnd) toTarget:self withObject:nil];
//
// pTheConnection = nil;
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Connection Error", #"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", #"")
otherButtonTitles:nil] show];
[self.urlConnection cancel];
[delegate DownloadFailed:-1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection cancel];
[delegate DownloadCompleted:self.recvdData];
}
DownloadRequest *request = [[DownloadRequest alloc] init];
request.delegate = self;
[request startDownloadFromURL:strURL];
I've already searched a lot but none of the tutorials and sample codes helped. I am trying to parse a very simple XML data, which will be always the same with just one result, the xml is code bellow:
<Books>
<Book id="1">
<title>USERS ALREADY EXISTS</title>
</Book>
</Books>
So, how can I parse such a file using NSXMLParser or another way you know?
Well I parse xml some different way than others and being frank I really do not know which technique it is but I assure you it works fine for me and I have implemeted it successfully in so many projects. Have a look at my code where I load tweets from some profile
This is the function where I make call for parser.
-(void)loadtweet
{
#try
{
NSString *urlString = [NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=SrBachchan&count=5"];
NSLog(#"fetching data from--------> : %#",urlString);
NSString* escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:request1 delegate:self];
if(con)
truckData=[[NSMutableData data]retain];
}
#catch (NSException *exception)
{
UIAlertView *v = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Please Try Again Later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[v show];
[v release];
}
}
And these are the NSURLConnection delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[truckData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[truckData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[tweets removeAllObjects];
#try
{
// [app.trucks removeAllObjects];
NSString *thexml=[[NSString alloc] initWithBytes:[truckData mutableBytes] length:[truckData length] encoding:NSUTF8StringEncoding];
NSArray *array=[thexml componentsSeparatedByString:#"<status>"];
NSLog(#"%d",[array count]);
for(int i=1;i<[array count];i++)
{
NSString *str=[array objectAtIndex:i];
NSArray *arr1=[str componentsSeparatedByString:#"<text>"];
NSString *data=[arr1 objectAtIndex:1];
NSRange ranfrom=[data rangeOfString:#"</text>"];
// nt.truckName=[data substringToIndex:ranfrom.location];
[tweets addObject:[data substringToIndex:ranfrom.location]];
}
}
#catch (NSException *exception)
{
UIAlertView *v = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Please Try Again Later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[v show];
[v release];
}
}
I have used some string functions to separate tags and stored the values in Array.
I want to fetch Google news data by XML parsing and save it into an array. The XML is like this
http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&output=rss
Well I parse xml some different way than others and being frank I really do not know which technique it is but I assure you it works fine for me and I have implemeted it successfully in so many projects. Have a look at my code where I load tweets from some profile
This is the function where I make call for parser.
-(void)loadtweet
{
#try
{
NSString *urlString = [NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=SrBachchan&count=5"];
NSLog(#"fetching data from--------> : %#",urlString);
NSString* escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:request1 delegate:self];
if(con)
truckData=[[NSMutableData data]retain];
}
#catch (NSException *exception)
{
UIAlertView *v = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Please Try Again Later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[v show];
[v release];
}
}
And these are the NSURLConnection delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[truckData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[truckData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[tweets removeAllObjects];
#try
{
// [app.trucks removeAllObjects];
NSString *thexml=[[NSString alloc] initWithBytes:[truckData mutableBytes] length:[truckData length] encoding:NSUTF8StringEncoding];
NSArray *array=[thexml componentsSeparatedByString:#"<status>"];
NSLog(#"%d",[array count]);
for(int i=1;i<[array count];i++)
{
NSString *str=[array objectAtIndex:i];
NSArray *arr1=[str componentsSeparatedByString:#"<text>"];
NSString *data=[arr1 objectAtIndex:1];
NSRange ranfrom=[data rangeOfString:#"</text>"];
// nt.truckName=[data substringToIndex:ranfrom.location];
[tweets addObject:[data substringToIndex:ranfrom.location]];
}
}
#catch (NSException *exception)
{
UIAlertView *v = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Please Try Again Later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[v show];
[v release];
}
}
I have used some string functions to separate tags and stored the values in Array.
This is where you can start: NSXMLParser class reference.
In my app im downloading some videos using NSURLConnection. It shows two memory warnings.
Received memory warning. Level=1
Received memory warning. Level=2
And then after sometime the App Crashes is there any way to solve this issue.
Can anyone help me with this issue.
Thanks in advance.
Code i used:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[exer1 objectAtIndex:i-1]]cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSLog(#"%# urlrequest ",theRequest);
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
HUD.labelText =[NSString stringWithFormat:#"Downloading %d Video",[exer1 count]-(i-1)];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
expectedLength = [response expectedContentLength];
currentLength = 0;
HUD.mode = MBProgressHUDModeDeterminate;
NSLog(#"%d expectedLength",expectedLength);
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
currentLength += [data length];
HUD.progress = currentLength / (float)expectedLength;
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[HUD hide:YES];
// release the connection, and the data object
// [connection release];
// receivedData is declared as a method instance elsewhere
// [receivedData release];
// inform the user
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
if(tempz == 1){
tempz =0;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"The Internet connection appears to be offline." message:nil delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *err;
NSFileManager *fman = [NSFileManager defaultManager];
NSString *path = [[[fman URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
NSDictionary *fattr = [fman attributesOfFileSystemForPath:path error:&err];
//Error checking
NSUInteger freeSize = [[fattr objectForKey:NSFileSystemFreeSize] unsignedIntegerValue];
NSLog(#"Free Space %d", freeSize);
NSArray* paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
struct statfs tStats;
statfs([[paths1 lastObject] cString], &tStats);
float total_space = (float)(tStats.f_blocks * tStats.f_bsize);
NSLog(#"%f total_space",total_space);
[SavedVid addObject:[exer1 objectAtIndex:i-1]];
NSUserDefaults *currentDefaults6 = [NSUserDefaults standardUserDefaults];
[currentDefaults6 setObject:[NSKeyedArchiver archivedDataWithRootObject:SavedVid] forKey:#"SavedVid"];
[currentDefaults6 synchronize];
NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:#"/Library/Caches"] ;
/* NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%# documentsDirectory",documentsDirectory);
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
*/
NSString *file2 = [NSString stringWithFormat:#"%#/%#.mp4",cacheDirectory,[elementw.description objectAtIndex:i-1]];
/* NSLog(#"%# documentsDirectory",file2);
NSLog(#"%# ---- i elementw.description ---- %d ",elementw.description,i);
*/
[receivedData writeToFile:file2 atomically:YES];
NSLog(#" %# file 2 ",file2);
HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]] autorelease];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:2];
[self initializPlayer];
// release the connection, and the data object
// [connection release];
// [receivedData release];
}
When the data is received, you need to store it in a temporary (or not-so-temporary) file. The problem is that the whole file is being download into memory, which would consume most of the memory.
The application crashes because it's using too much memory, so writing to a file is the best option.
Something like this:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
currentLength += [data length];
HUD.progress = currentLength / (float)expectedLength;
NSString *temporaryFile = [NSString stringWithFormat:#"%#/fileDownload.part", NSTemporaryDirectory()];
if (![[NSFileManager defaultManager] fileExistsAtPath:temporaryFile]) {
[[NSFileManager defaultManager] createFileAtPath:temporaryFile contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:temporaryFile];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
if (currentLength == expectedLength) {
//read from the file stored at temporaryFile
//perhaps move to a permanent location and change
//its file name and extension.
}
}
I think you are keeping the Video in your memory. Depending on the size it can cause memory problems.
I am a fresher. I don't know how to use JSON for Parsing .I am really very confuse because the tutorial i have read are out dated because apple has deprecated all the API's and documents .Thats what i found .So anyone can give me the start to play with JSON?
You can use SBJSON
You can find code at GITHUB
Here's some links on "Picking the best JSON library":
Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
Best JSON library to use when developing an iPhone application?
And now for the shameless plug for my own JSON parsing solution, JSONKit:
What's the most efficient way of converting a 10 MB JSON response into an NSDictionary?
Cocoa JSON parsing libraries, part 2
You need to use third-party code to parse JSON. Three popular libraries/frameworks are:
SBJSON, aka json-framework
TouchJSON
yajl-objc
Choose one of them, download its source code and add it do your project.
You can use your custom framwork for it just as below
#import <Foundation/Foundation.h>
#import "SVProgressHUD.h"
#protocol JsonDataDelegate <NSObject>
#required
- (void) JsonprocessSuccessful: (NSString *)receivedData;
-(void) JsonprocessFail;
#end
#interface JsonRest : NSObject
{
id <JsonDataDelegate> delegate;
NSURLConnection *theConnection;
NSMutableData *webData;
BOOL HadGotResponse;
BOOL HasFailedConnection;
UIAlertView *alert;
}
#property (retain) id delegate;
#property(nonatomic,retain) NSURLConnection *theConnection;
#property (nonatomic)BOOL HadGotResponse;
#property (nonatomic)BOOL HasFailedConnection;
-(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter;
-(void)Set2Defaults;
#end
#import "JsonRest.h"
#define BASE_URL #"http://www.abc.com"
#define DOMAIN #"GETLIST"
#implementation JsonRest
#synthesize delegate,HadGotResponse,HasFailedConnection,theConnection;
- (id)init
{
if (self)
{
// Initialization code.
//appdel = (ReachCastAppDelegate*)[[UIApplication sharedApplication]delegate];
}
return self;
}
-(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter
{
[SVProgressHUD startActivity : #"Loading..."];
NSString *strUrl=[NSString stringWithFormat:#"%#%#?%#",BASE_URL,url,parameter];
NSURL *url1=[NSURL URLWithString:strUrl];
NSLog(#"domainURL :: %#",strUrl);
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
[req setTimeoutInterval:60.0];
[req setHTTPMethod:#"GET"];
// if([HttpMethod isEqualToString:#"GET"])
// {
// [req setHTTPMethod:HttpMethod];
//
// }
// else if([HttpMethod isEqualToString:#"PUT"])
// {
// NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
//
// [req setValue:valueforput forHTTPHeaderField:#"Content-type"];
// [req setHTTPMethod:HttpMethod];
// [req setHTTPBody: requestData];
//
// }
// else if ([HttpMethod isEqualToString:#"POST"]){
//
// NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
//
// [req setValue:valueforput forHTTPHeaderField:#"Content-type"];
// [req setHTTPMethod:HttpMethod];
// [req setHTTPBody: requestData];
//
// }
if(theConnection)
[self Set2Defaults];
theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(theConnection)
webData=[[NSMutableData data]retain];
else
NSLog(#"Connection Failed !!!");
NSLog(#"Has got response");
}
-(void)Set2Defaults {
if (webData != nil){
[webData release];
webData = nil;
}
if (theConnection != nil) {
[theConnection release];
if (theConnection != nil)
theConnection = nil;
}
}
#pragma mark -
#pragma mark NSURL Connection Delegate methods
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) respons{
[webData setLength: 0];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)respons;
int statusCode = [httpResponse statusCode];
NSLog(#"statusCode ---- >> %d",statusCode);
if (200 != statusCode) {
// if (401 == statusCode) {
}
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
[SVProgressHUD stopActivity];
[self Set2Defaults];
self.HadGotResponse=NO;
self.HasFailedConnection=YES;
// txtWindSpeed.text = #"";
[[self delegate] JsonprocessFail];
NSLog(#"Connection Failed!!!");
//[self HideLoadingDialogue];
alert = [[[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Internet Connection Failed.Please try again." delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
//alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, 130);
NSLog(#"%F",alert.frame.origin.y);
[alert show];
alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y+25, alert.frame.size.width, 130);
//[noConnect release];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(timerCall) userInfo:nil repeats:NO];
}
-(void)timerCall
{
[alert dismissWithClickedButtonIndex:0 animated:TRUE];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[SVProgressHUD stopActivity];
self.HasFailedConnection=NO;
NSString *theXML;
theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSASCIIStringEncoding];
//NSLog(#"theXML Values : %#", theXML);
//self.ResponseDict = [theXML JSONValue];
[[self delegate] JsonprocessSuccessful:theXML];
[theXML release];
}
-(void)dealloc
{
if (webData != nil){
[webData release];
webData = nil;
}
if (theConnection != nil) {
[theConnection release];
if (theConnection != nil)
theConnection = nil;
}
[super dealloc];
// [ResponseDict release];
}
#end
You can use this using below
-(void)getJsonCalling
{
#try {
NSString *strParameter=[NSString stringWithFormat:#"param1=%#¶m2=%#",param1,param2];
objJsonRest=[[JsonRest alloc]init];
[objJsonRest setDelegate:self];
[objJsonRest GetServiceCall:DOMAIN Paraqmeter:strParameter];
[objJsonRest release];
}
#catch (NSException *exception) {
NSLog(#"Exception in %s %#",__FUNCTION__,exception);
}
}
- (void) JsonprocessSuccessful: (NSString *)receivedData
{
}
-(void) JsonprocessFail;
{
NSLog(#"FAIL");
}