ios - How to handle NSURLConnectionDelegate? - ios

I'm trying to get token with the help of given link. Please go through this link http://www.stevesaxon.me/posts/2011/window-external-notify-in-ios-uiwebview/
What is _data here? How to declare that?
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if(_data)
{
[_data release];
_data = nil;
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if(!_data)
{
_data = [data mutableCopy];
}
else
{
[_data appendData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
[_data release];
_data = nil;
// prepend the HTML with our custom JavaScript
content = [ScriptNotify stringByAppendingString:content];
[_webView loadHTMLString:content baseURL:_url];
}
}

Its NSMutablData Object which holds the response Data which you receive from your Request to Webservice
Declare this in #interface of .h file
NSMutableData *_data;
#property (nonatomic, retain) NSMutableData *_data;
and #synthesize _data; in .m file after #implementation line

Related

Json response is giving wrong data

I am calling the webservice string using the NSURLConnection , I am getting wrong data in response in success method of NSURLConnection , But if i load same URL in browser i am getting correct response. I am using below code .
NSData *mydata=[srtRes dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *returnArry =[[NSMutableArray alloc]init];
returnArry = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:&e];
How to resolve this issue. Kindly give suggestion and answers.
Try this one :
// In .h class
#property (nonatomic,retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *temp_arr;
// In .m class
#synthesize responseData;
#synthesize temp_arr;
- (void)viewDidLoad
{
NSString *urlString=#"http://your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
}
Delegate Method of JSON Parsing :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray * returnArry = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
NSDictionary *nameDic = nil;
for (int i = 0 ; i < [returnArry count]; i++)
{
nameDic = [returnArry objectAtIndex:i];
[self.temp_arr addObject:[nameDic objectForKey:#"name"]]; // According your key you have to save data in temp_arr.
}
}
Please follow this , if any doubt let me know :)

Saving Variable value outside of Connection didReceiveData Ùdelagate Method

I have tried to find a similar question but I was unable to do so. I have a singleton that is used to gather information through out my app. Once of the values is obtained within the following method.
-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
In this method I get the response from th webservice that I am trying to connect to. Everything is good. However any attempt to save the variable value to my singleton fails. Within this method no problem. When I try to get to the next view and reference my singleton, it is as if the value never gets saved.
Here is a skeleton of my code.
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
Basically the goal here is to have the hosted payment page appear in the next view. The flow flow for that works. I just need to pass the URI link so that payment can be made.
I know that I can return a value from this delegate method, but since I never explicitly call this method, so I am unsure where it is being called. Probably the reason why my values are not being saved in the singleton class.
EDIT:
Right now I have one view which does all of the action.
//
// NBXViewController.h file
#import <UIKit/UIKit.h>
#interface NBXViewController : UIViewController
//*************************************************
// Variables to be declared for NBXViewController *
//*************************************************
#property (strong, nonatomic) IBOutlet UILabel *storeLabel;
#property (strong, nonatomic) IBOutlet UIButton *purchaseButton;
#property (strong, nonatomic) IBOutlet NSString *hostedURL;
//*************************************************
// Button Action methods for the buttons on View *
//*************************************************
- (IBAction)puchaseButtonAction:(id)sender;
//*************************************************
// Connection Delegate Methods *
//*************************************************
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; // Handle Connection Error
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; // Data Received from Connection (Header Information)
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; //Response from Connection (Return from Hosted being called)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection; // Coonection did finish loading
#end
Implementation file.
//
// NBXViewController.m
// HostedAPI
//
// Created by Philip Teoli on 3/1/2014.
// Copyright (c) 2014 Philip Teoli. All rights reserved.
//
#import "NBXViewController.h"
#import "NBXJSONResponse.h"
#interface NBXViewController ()
#end
#implementation NBXViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//****************************************
// PurchaseButton Action Method *
//****************************************
- (IBAction)puchaseButtonAction:(id)sender
{
//************************************
// Building JSON Request *
//************************************
NSString *jsonString = #"Sample Request";
//**************************************
// Convert JSON String to NSData *
//**************************************
NSData* jsonRequestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//**************************************
// Creating JSON object to Send *
//**************************************
NSString *jsonRequest = [[NSString alloc] initWithData:jsonRequestData encoding:NSUTF8StringEncoding];
//*****************************************
// Base64 Encoding for Application Header *
//*****************************************
NSString *base64Signature = #"NbMIIkomZ8mFNw97EGRT:NAA5e965731e8a27ab11f5f";
NSString *basic = #"Basic: ";
NSData *base64SignatureData = [base64Signature dataUsingEncoding: NSUTF8StringEncoding];
NSString *base64SignatureEncoded = [base64SignatureData base64EncodedStringWithOptions:0];
NSString *header = nil;
header = [basic stringByAppendingString:base64SignatureEncoded];
// NSLog(#"Encoded Header: %#", header);
//*************************************
// Preparing to send XML through POST *
//*************************************
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonRequest length]]; //Calculating the Content Length
NSData *postData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; // preapring JSON Request to be sent
//**************************************
// Headers and POST Body *
//**************************************
NSURL *serviceUrl = [NSURL URLWithString:#"https://pay.test.ewbservice.com/orders"];
NSMutableURLRequest *serviceRequest=[NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[serviceRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serviceRequest setValue:header forHTTPHeaderField:#"Authorization"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:serviceRequest
delegate:self startImmediately:YES];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
NSLog(#"Hosted URL in Button: %#", _hostedURL);
}
//****************************************************
// Implementation of Connection Delegate Methods *
//****************************************************
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"did fail");
}
//*******************************************************
// Connection Data Received *
//*******************************************************
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData: [dataResponse dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
//********************************
// Iterating through Dictionary *
//********************************
NSArray *jsonLink = nil;
for(id key in jsonDictionary)
{
if ([key isEqualToString:#"link"])
{
jsonLink = [jsonDictionary objectForKey:key]; // this returns a dictionary. Will need to parse dictionary another 2 times to get proper URI.
}
}
NSDictionary *test = [jsonLink objectAtIndex:0];
for(id key in test)
{
if ([key isEqualToString:#"uri"])
{
_hostedURL = [test objectForKey:key];
}
}
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
}
//*******************************************************
// Connection Response Method *
//*******************************************************
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"did receive response: \n %#", response);
NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];
}
//*******************************************************
// Connection Finished Loading Data Method *
//*******************************************************
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"did finish loading!!! \n%#", _hostedURL);
// NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
// [jsonResponse setHostedURL:_hostedURL];
}
#end
Please let me know of your thoughts. I can post more details if needed. Thanks in advance for your help!!!
Regards,
Thanks to the great help from #rdelmar I was able to get through this. Basically in short what was happening was that I was going to the next view before the information was received by my previous view from the web service. So when I was trying to change a label with a value to my Singleton, it was not stored yet. How I got around the issue is that when I click a button I wait until the web services responses and then I add a view to go to the new view. Now my URL that I was waiting reaches me, I save it to Singleton and then I go to the next view.
I will add my code once I can grab it and post it.
Thanks again for all of your help Eric!!! Your patience and help make you a great person on this community.
Regards,
Corporate One

Can't reload data in tableView after parsing XML

I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In connectionDidFinishLoading I'm trying [self.tableView reloadData, but it doesn't work. This is my code:
my .h file:
#interface catalogViewController : UITableViewController //
#property (nonatomic, strong) NSMutableData *receivedData;
#property (nonatomic,retain) NSArray * titleArr;
#property (nonatomic,retain) NSArray * contentArr;
#property (nonatomic,retain) NSArray * ImageURLArr;
#property (nonatomic,retain) NSArray * dateArr;
#property (nonatomic,retain) NSArray * priceArr;
#property (nonatomic,retain) NSDictionary * xmlDictionary;
#property (nonatomic,retain) NSArray * IDArr;
#property (nonatomic) BOOL * didDataLoaded;
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
_titleArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"];
_IDArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"];
_priceArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"];
_ImageURLArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
XML downloading - OK, parsing - OK, initialising arrays - OK. But when I start project I have exception on the line NSLog(#"%#", self.titleArr objectAtIndex:indexPath.row]; - says: "Thread 1: EXC_BAD_ACCESS (code 1)
How can I understand it's means that it's trying initialize array when it's not prepare. My problem is i can't delay tableView methods or what? How can i fix it? I'm trying fix itfor some days...
Your titleArr is deallocated from memory and then you are requesting object of it so it is giving you a crash. So allocate memory to array by this way.
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
Eventhough it's not recommended way but the following can provide a solution to you
self.tableView.delegate = nil;
self.tableView.datasource = nil;
and when safely your array was populated with the xml data set back to
self.tableView.delegate = self;
self.tableView.datasource = self;

App getting frozen while parsing json

I am parsing 5 urls here using NSURLConnection delegate which retrieves json from mysql db & inserts into core data to DB while user logs in. But the code is taking too much time,how can I reduce time here please help.
dispatch_queue_t myBackgroundQueue;
myBackgroundQueue = dispatch_queue_create("loginTask", NULL);
dispatch_async(myBackgroundQueue, ^(void){
// code for parsing 5 urls
json_parser *obj= [[json_parser alloc]init];
[obj parseUrl:#"myurl"];
});
#interface json_parser () {
NSMutableArray *array;
NSMutableData *mdata;
NSURLConnection *conn;
}
#end
#implementation json_parser
- (void)parseUrl:(NSString *)baseUrl
{
NSURL *url=[NSURL URLWithString:baseUrl];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
conn=[NSURLConnection connectionWithRequest:request delegate:self];
if(conn) {
mdata=[[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[mdata setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:mdata options:0 error:nil];
for (NSDictionary *dict in allData)
{
masterGeneric *masterObj=[[masterGeneric alloc]init];//this is nsobject type class
masterObj.masterId=[dict objectForKey:#"id"];
masterObj.genericname=[dict objectForKey:#"genericname"];
masterObj.salient_features=[dict objectForKey:#"salient_features"];
masterObj.bioactivity_group=[dict objectForKey:#"bioactivity_group"];
masterObj.therapy_group=[dict objectForKey:#"therapy_group"];
masterObj.dosage_information=[dict objectForKey:#"dosage_information"];
masterObj.indications=[dict objectForKey:#"indications"];
masterObj.food=[dict objectForKey:#"food"];
masterObj.interaction=[dict objectForKey:#"interaction"];
masterObj.side_effects=[dict objectForKey:#"side_effects"];
masterObj.precautions=[dict objectForKey:#"precautions"];
masterObj.warnings=[dict objectForKey:#"warnings"];
masterObj.advice_to_patients=[dict objectForKey:#"advice_to_patients"];
masterObj.route_of_administration=[dict objectForKey:#"route_of_administration"];
masterObj.available_form=[dict objectForKey:#"available_form"];
}
}

Download with NSURLConnection returns empty data?

My app is downloading a file from the internet using NSURLConnection.
Two problems are happening:
1) [connection didReceiveData] is never called
2) When [connection didFinishDownloading] is called, my self.currentData is empty
What am I doing wrong?
My header looks like this:
#interface DIFileDownloader : NSObject <NSURLConnectionDelegate> {
NSMutableData *currentData;
}
#property (nonatomic, assign) id <DIFileDownloaderDelegate> delegate;
#property (nonatomic, retain) NSMutableArray *supportedFormats;
#property (nonatomic, retain) NSMutableData *currentData;
#property (nonatomic, retain) NSURLConnection *downloadAgent;
#property (nonatomic) long long expectedContentSize;
#property (nonatomic) float currentDownloadProgress;
#property (nonatomic, getter = isRunning) BOOL running;
-(instancetype)initWithSupportedFormats:(NSArray *)extensions;
-(void)downloadFileAtURL:(NSURL *)url;
-(NSString *)documentsDirectoryPath;
#end
And my implementation file:
-(instancetype)initWithSupportedFormats:(NSArray *)extensions {
self.supportedFormats = [[NSMutableArray alloc] initWithArray:extensions];
self.running = NO;
}
-(void)downloadFileAtURL:(NSURL *)url {
NSString *fileExtension = [url pathExtension];
if ([self.supportedFormats containsObject:fileExtension]) {
self.downloadAgent = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
[self.downloadAgent start];
NSLog(#"Beginning download at URL:%#", url.absoluteString);
}
else {
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Connection recieved response with size: %f", (float)[response expectedContentLength]);
self.expectedContentSize = (float)[response expectedContentLength];
self.running = YES;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"%i", [httpResponse statusCode]);
/*
if ([httpResponse statusCode] >= 200 && [httpResponse statusCode] <= 299) {
}
*/
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"%f", (float)[data length]);
[currentData appendData:data];
self.currentDownloadProgress = ((float)[data length] / self.currentDownloadProgress);
NSLog(#"Connection recieved data. New progress is: %f", self.currentDownloadProgress);
if ([self.delegate respondsToSelector:#selector(downloader:progressChanged:)]) {
[self.delegate downloader:self progressChanged:self.currentDownloadProgress];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed");
if ([self.delegate respondsToSelector:#selector(downloader:failedToDownloadFileAtURL:reason:)]) {
[self.delegate downloader:self failedToDownloadFileAtURL:connection.originalRequest.URL reason:error];
}
}
-(void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL {
NSLog(#"Connection finished downloading with size: %f", (float)[currentData length]);
self.running = NO;
NSString *filename = [destinationURL.absoluteString lastPathComponent];
NSString *docPath = [self documentsDirectoryPath];
NSString *pathToDownloadTo = [NSString stringWithFormat:#"%#/%#", docPath, filename];
NSError *error = nil;
[currentData writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
if (error != nil) {
NSLog(#"DIFileDownloader: Failed to save the file because: %#", [error description]);
if ([self.delegate respondsToSelector:#selector(downloader:failedToDownloadFileAtURL:reason:)]) {
[self.delegate downloader:self failedToDownloadFileAtURL:connection.originalRequest.URL reason:error];
}
}
else {
if ([self.delegate respondsToSelector:#selector(downloader:finishedDownloadingFileNamed:atPath:)]) {
[self.delegate downloader:self finishedDownloadingFileNamed:filename atPath:pathToDownloadTo];
}
}
}
- (NSString *)documentsDirectoryPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return documentsDirectoryPath;
}
#end
As mentioned in others and in my comment, there are a few bugs in your code which you need to fix.
But there is also one big misconception - stemming from the former awful documentation of NSURLConnection:
connectionDidFinishDownloading:destinationURL: is NOT a delegate method of the two delegates of NSURLConnection namely, NSURLConnectionDelegate and NSURLConnectionDataDelegate which you are supposed to implement in your case.
The minimal set of delegate methods you need to implement are:
For the NSURLConnectionDelegate:
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
then for the NSURLConnectionDataDelegate:
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
(void)connectionDidFinishLoading:(NSURLConnection*)connection;
If you don't mind, I've put a sample of a minimal implementation on Gist: SimpleGetHTTPRequest which should give you a jump start do implement your own HTTP request class.

Resources