Push TableView Url to webView - iphone

i have a problem with my table, i use LazyTableImages example from Apple before embed into my project.
Every work fine when load my xml like this
<im:title>1</im:title>
<content type="html">some desc</content>
<im:releaseDate label="October 23, 2013">2013-10-23T00:00:00-07:00</im:releaseDate>
<im:artist href="http:/facebook.com">Facebook</im:artist>
<im:name>1</im:name>
<im:image height="53">http://chingfong.com/Icon.png</im:image>
<url>http://facebook.com/url>
<im:date>Ene, 27 2013</im:date>
and here is my AppRecord.h
#property (nonatomic, strong) NSString *appName;
#property (nonatomic, strong) UIImage *appIcon;
#property (nonatomic, strong) NSString *artist;
#property (nonatomic, strong) NSString *imageURLString;
#property (nonatomic, strong) NSString *appURLString;
#property (nonatomic, strong) NSString *appURL;
ParseOperation.h - i also added
static NSString *kUrlStr = #"url";
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if (self.workingEntry)
{
if (self.storingCharacterData)
{
NSString *trimmedString = [self.workingPropertyString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.workingPropertyString setString:#""]; // clear the string for next time
if ([elementName isEqualToString:kIDStr])
{
self.workingEntry.appURLString = trimmedString;
}
else if ([elementName isEqualToString:kNameStr])
{
self.workingEntry.appName = trimmedString;
}
else if ([elementName isEqualToString:kImageStr])
{
self.workingEntry.imageURLString = trimmedString;
}
else if ([elementName isEqualToString:kUrlStr])
{
self.workingEntry.appURL = trimmedString;
}
else if ([elementName isEqualToString:kArtistStr])
{
self.workingEntry.artist = trimmedString;
}
}
else if ([elementName isEqualToString:kEntryStr])
{
[self.workingArray addObject:self.workingEntry];
self.workingEntry = nil;
}
}
}
RootViewController.m in tableView didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
AppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
NSString *urlAddress = appRecord.appURL;
NSURL *url = [NSURL URLWithString:urlAddress];
WebViewController *detailViewController = [[WebViewController alloc] initWithNibName:#"WebViewController" bundle:nil];
// WebViewController.sites= [_entries objectAtIndex:indexPath.row];
[detailViewController.webView loadRequest:[NSURLRequest requestWithURL:url]];
[self.navigationController pushViewController:detailViewController animated:YES];
}
WebViewController.h
#interface WebViewController : UIViewController <UIWebViewDelegate>
#property (nonatomic, strong) IBOutlet UIWebView *webView;
The table load fine, and it push to WebViewController when i selected cell but the UIWebView didn't load the web page, it's only blank (white).
can anyone help me to fix it?
thanks so much!

I think the best way for you is to pass the url from RootViewController to WebViewController and refresh your webview in WebViewController.
So you need to modify your code like this :
RootViewController.m in tableView didSelectRowAtIndexPath
// Add a #property of your detail view for lazing
#property (nonatomic, strong) WebViewController *detailViewController;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
AppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
if (!_detailViewController)
self.detailViewController = [[WebViewController alloc] initWithNibName:#"WebViewController" bundle:nil];
self.detailViewController.websiteURL = appRecord.appURL;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
WebViewController.h
#interface WebViewController : UIViewController <UIWebViewDelegate>
#property (nonatomic, strong) IBOutlet UIWebView *webView;
#property (nonatomic, strong) NSString *websiteURL;
WebViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:_websiteURL]];
// Load the request in the UIWebView
[_webView loadRequest:requestObj];
}

Related

I Can't Insert an Object in a NSMutableArray when I parse a XML

The Code:
...
else if ([elementName isEqualToString:#"photo"]) {
NSLog(#"Trying to add photo");
NSLog(#"Prev: %d",[currentItem.photoList count]);
NSLog(#"Author: %#",[currentPhotoItem author ]);
[currentItem.photoList addObject:currentPhotoItem];
NSLog(#"Next: %d",[currentItem.photoList count]);
}
The Log:
2011-10-11 09:49:13.553 ECG[4862:b303] Trying to add photo
2011-10-11 09:49:13.553 ECG[4862:b303] Prev: 0
2011-10-11 09:49:13.554 ECG[4862:b303] Author: Fernando Blanco
2011-10-11 09:49:13.573 ECG[4862:b303] Next: 0
The method addObject doesn't add objects to the NSMutableArray...
"photoList" is a NSMutableString defined in the class:
#interface GalleryRSSItem : NSObject {
NSString *title;
NSString *imgtn;
NSString *category;
NSString *url;
NSString *date;
NSMutableArray *photoList;
}
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *imgtn;
#property (nonatomic, retain) NSString *category;
#property (nonatomic, retain) NSString *url;
#property (nonatomic, retain) NSString *date;
#property (nonatomic, retain) NSMutableArray *photoList;
#end
And the objects are initialized in the parser didStartElemnt method
- (void) parser:(NSXMLParser *) Parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"gallery"]) {
currentItem = [[GalleryRSSItem alloc] init];
currentNodeContent = [[NSMutableArray alloc] init];
}
if ([elementName isEqualToString:#"photo"]) {
currentPhotoItem = [[PhotoRSSItem alloc] init];
currentNodeContent = [[NSMutableArray alloc] init];
}
}
Check if you have properly initialized currentItem.photoList array.
I guess, either currentItem or currentItem.photoList is NIL. Obj-C allows to call methods on nil objects and the count call will return 0 in such case.

When manual reload viewDidLoad how clear memory and using viewDidUnload

Help find out how to solve the problem using the memory in my application, may have another way to implement my task.
Have the following code:
Constants.h
#import <Foundation/Foundation.h>
extern NSString * const ITEM;
extern NSString * const TITLE;
extern NSString * const IMAGE;
extern NSString * const DESCRIPTION;
extern NSString * const TEXT;
#interface Constants : NSObject
{
}
#end
Constants.m
#import "Constants.h"
#implementation Constants
NSString * const ITEM = #"item";
NSString * const TITLE = #"title";
NSString * const IMAGE = #"image";
NSString * const DESCRIPTION = #"description";
NSString * const TEXT = #"text";
- (void)dealloc
{
[super dealloc];
}
#end
myNews.h
#import <Foundation/Foundation.h>
#interface myNews : NSObject
{
NSString *itemTitle;
NSString *itemImageUrl;
NSString *itemDescription;
NSString *itemText;
}
#property (nonatomic, retain) NSString *itemTitle;
#property (nonatomic, retain) NSString *itemImageUrl;
#property (nonatomic, retain) NSString *itemDescription;
#property (nonatomic, retain) NSString *itemText;
#end
myNews.m
#import "myNews.h"
#implementation myNews
#synthesize itemTitle;
#synthesize itemImageUrl;
#synthesize itemDescription;
#synthesize itemText;
#end
XMLController.h
#import <Foundation/Foundation.h>
#class Constants;
#class myNews;
#interface XMLController : NSObject
{
NSMutableString *currentNodeContent;
NSMutableArray *newsArray;
NSXMLParser *parser;
myNews *currentNew;
}
#property (readonly, retain) NSMutableArray *newsArray;
-(id)loadXMLByURL:(NSString *)urlString;
#end
XMLController.m
#import "XMLController.h"
#import "Constants.h"
#import "myNews.h"
#implementation XMLController
#synthesize newsArray;
-(id)loadXMLByURL:(NSString *)urlString
{
newsArray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString: urlString];
parser = [[NSXMLParser alloc] initWithContentsOfURL: url];
[parser setDelegate:(id)self];
[parser parse];
return self;
}
-(void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString: ITEM])
{
currentNew = [myNews alloc];
currentNodeContent = [[NSMutableArray alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString: TITLE])
{
currentNew.itemTitle = currentNodeContent;
}
if ([elementName isEqualToString: IMAGE])
{
currentNew.itemImageUrl = currentNodeContent;
}
if ([elementName isEqualToString: DESCRIPTION])
{
currentNew.itemDescription = currentNodeContent;
}
if ([elementName isEqualToString: TEXT])
{
currentNew.itemText = currentNodeContent;
}
if ([elementName isEqualToString: ITEM])
{
[newsArray addObject:currentNew];
[currentNew release];
currentNew = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
-(void) parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
currentNodeContent = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
myAppDelegate.h
#import <UIKit/UIKit.h>
#import "MainViewController.h"
#import "DetailViewController.h"
#class MainViewController;
#class DetailViewController;
#interface myAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *myNavigationController;
MainViewController *myMainViewController;
DetailViewController *myDetailViewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *myNavigationController;
#property (nonatomic, retain) IBOutlet MainViewController *myMainViewController;
#property (nonatomic, retain) IBOutlet DetailViewController *myDetailViewController;
#end
myAppDelegate.m
#import "myAppDelegate.h"
#import "myNews.h"
#import "MainViewController.h"
#import "DetailViewController.h"
#implementation myAppDelegate
#synthesize window;
#synthesize myNavigationController;
#synthesize myMainViewController;
#synthesize myDetailViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[window addSubview:myNavigationController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[window release];
[myNavigationController release];
[myMainViewController release];
[myDetailViewController release];
[super dealloc];
}
#end
MainViewController.h
#import <UIKit/UIKit.h>
#import "XMLController.h"
#interface MainViewController : UIViewController
{
XMLController *xmlcont;
UILabel *myTitleLabel;
// declared here some 10 objects
}
#property (nonatomic, retain) UILabel *myTitleLabel;
#end
MainViewController.m
#import "MainViewController.h"
#import "myNews.h"
#implementation MainViewController
#synthesize myTitleLabel;
- (void)completeRefresh
{
[myMainViewController viewDidLoad];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myRefreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 35.0f, 23.0f)];
[myRefreshButton setImage:[UIImage imageNamed:#"ButtonRefresh.png"] forState:UIControlStateNormal];
[myRefreshButton addTarget:self
action:#selector(completeRefresh)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *myRefreshBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myRefreshButton] autorelease];
[self.navigationItem setRightBarButtonItem: myRefreshBarButton];
[myRefreshButton release];
xmlcont = [[XMLController alloc] loadXMLByURL:#"http://link_to_XML_file.xml"];
NSLog(#"array = %#", [xmlcont newsArray]);
for (myNews *oneNew in [xmlcont newsArray]) {
CGRect frameTitleLabel = CGRectMake(0.0f, 200.0f, 320.0f, 60.0f);
myTitleLabel = [[UILabel alloc] initWithFrame:frameTitleLabel];
myTitleLabel.backgroundColor = [UIColor blackColor];
myTitleLabel.text = [myOneNew itemTitle];
myTitleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size: 17.0];
myTitleLabel.textColor = [UIColor whiteColor];
[self.view addSubview:myTitleLabel];
[myTitleLabel release];
}
}
- (void)viewDidUnload
{
self.myTitleLabel = nil;
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[myTitleLabel release];
[super dealloc];
}
#end
During the test the application using the Instruments: Activity Monitor shows that when you click refresh and call 'completeRefresh' memory (Real Mem) is not cleared when reload viewDidLoad, and accumulates with every touch and calling 'completeRefresh'
Maybe someone has a possible solution?
To avoid leaking memory you need to release your retained ivars/properties in dealloc. For example:
myNews.m
- (void)dealloc {
// Setting these properties to nil releases them because they're (nonatomic, retain)
self.itemTitle = nil;
self.itemImageUrl = nil;
self.itemDescription = nil;
self.itemText = nil;
[super dealloc];
}
XMLController.m
- (void)dealloc {
self.newsArray = nil;
// These ivars aren't properties so you just have to call release on them
[currentNodeContent release];
[parser release];
[currentNew release];
[super dealloc];
}
etc. Do this for all your classes.

NSXMLParser: Parsing XML file shows two identical arrays

Maybe someone can help ...
I have a problem with the fact that during the parsing of the XML file we have two arrays. Such is the construction of TWO identical returns an array:
xmlcont = [[XMLController alloc] loadXMLByURL:#"http://link_to_XML_file.xml"];
I have the following files:
Constants.h
#import <Foundation/Foundation.h>
extern NSString * const ITEM;
extern NSString * const TITLE;
extern NSString * const IMAGE;
extern NSString * const DESCRIPTION;
extern NSString * const TEXT;
#interface Constants : NSObject
{
}
#end
Constants.m
#import "Constants.h"
#implementation Constants
NSString * const ITEM = #"item";
NSString * const TITLE = #"title";
NSString * const IMAGE = #"image";
NSString * const DESCRIPTION = #"description";
NSString * const TEXT = #"text";
- (void)dealloc
{
[super dealloc];
}
#end
myNews.h
#import <Foundation/Foundation.h>
#interface myNews : NSObject
{
NSString *itemTitle;
NSString *itemImageUrl;
NSString *itemDescription;
NSString *itemText;
}
#property (nonatomic, retain) NSString *itemTitle;
#property (nonatomic, retain) NSString *itemImageUrl;
#property (nonatomic, retain) NSString *itemDescription;
#property (nonatomic, retain) NSString *itemText;
#end
myNews.m
#import "myNews.h"
#implementation myNews
#synthesize itemTitle;
#synthesize itemImageUrl;
#synthesize itemDescription;
#synthesize itemText;
#end
XMLController.h
#import <Foundation/Foundation.h>
#class Constants;
#class myNews;
#interface XMLController : NSObject
{
NSMutableString *currentNodeContent;
NSMutableArray *newsArray;
NSXMLParser *parser;
myNews *currentNew;
}
#property (readonly, retain) NSMutableArray *newsArray;
-(id)loadXMLByURL:(NSString *)urlString;
#end
XMLController.m
#import "XMLController.h"
#import "Constants.h"
#import "myNews.h"
#implementation XMLController
#synthesize newsArray;
-(id)loadXMLByURL:(NSString *)urlString
{
newsArray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString: urlString];
parser = [[NSXMLParser alloc] initWithContentsOfURL: url];
[parser setDelegate:(id)self];
[parser parse];
return self;
}
-(void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString: ITEM])
{
currentNew = [myNews alloc];
currentNodeContent = [[NSMutableArray alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString: TITLE])
{
currentNew.itemTitle = currentNodeContent;
}
if ([elementName isEqualToString: IMAGE])
{
currentNew.itemImageUrl = currentNodeContent;
}
if ([elementName isEqualToString: DESCRIPTION])
{
currentNew.itemDescription = currentNodeContent;
}
if ([elementName isEqualToString: TEXT])
{
currentNew.itemText = currentNodeContent;
}
if ([elementName isEqualToString: ITEM])
{
[newsArray addObject:currentNew];
[currentNew release];
currentNew = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
-(void) parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
currentNodeContent = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
myAppDelegate.h
#import <UIKit/UIKit.h>
#import "MainViewController.h"
#import "DetailViewController.h"
#class MainViewController;
#class DetailViewController;
#interface myAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *myNavigationController;
MainViewController *myMainViewController;
DetailViewController *myDetailViewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *myNavigationController;
#property (nonatomic, retain) IBOutlet MainViewController *myMainViewController;
#property (nonatomic, retain) IBOutlet DetailViewController *myDetailViewController;
#end
myAppDelegate.m
#import "myAppDelegate.h"
#import "myNews.h"
#import "MainViewController.h"
#import "DetailViewController.h"
#implementation myAppDelegate
#synthesize window;
#synthesize myNavigationController;
#synthesize myMainViewController;
#synthesize myDetailViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[window addSubview:myNavigationController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[window release];
[myNavigationController release];
[myMainViewController release];
[myDetailViewController release];
[super dealloc];
}
#end
MainViewController.h
#import <UIKit/UIKit.h>
#import "XMLController.h"
#interface MainViewController : UIViewController
{
XMLController *xmlcont;
}
#end
MainViewController.m
#import "MainViewController.h"
#import "myNews.h"
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
xmlcont = [[XMLController alloc] loadXMLByURL:#"http://link_to_XML_file.xml"];
NSLog(#"array = %#", [xmlcont newsArray]);
for (myNews *oneNew in [xmlcont newsArray]) {
NSLog(#"URL = %#", [oneNew itemImageUrl]);
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[super dealloc];
}
#end
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<channel>
<item>
<title>news 1</title>
<image>http://link_to_JPG_file_1.jpg</image>
<description>description 1</description>
<text>text 1</text>
</item>
<item>
<title>news 2</title>
<image>http://link_to_JPG_file_2.jpg</image>
<description>description 2</description>
<text>text 2</text>
</item>
</channel>
As a result, the implementation of the output I see:
2011-07-14 13:18:27.785 my[18673:207] array = (
"<myNews: 0x4e28dc0>",
"<myNews: 0x4e29080>"
)
2011-07-14 13:18:27.787 my[18673:207] URL = http://link_to_JPG_file_1.jpg
2011-07-14 13:18:27.818 my[18673:207] URL = http://link_to_JPG_file_2.jpg
2011-07-14 13:18:27.959 my[18673:207] array = (
"<myNews: 0x4b5a010>",
"<myNews: 0x4b5a310>"
)
2011-07-14 13:18:27.960 my[18673:207] URL = http://link_to_JPG_file_1.jpg
2011-07-14 13:18:27.963 my[18673:207] URL = http://link_to_JPG_file_2.jpg
MainWindow.xib
Screenshot MainWindow.xib
Please tell me where I could be wrong?
You're getting viewDidLoad called twice (which isn't necessarily a bug). You just need to add some logic to only load your XML once.
- (void)viewDidLoad
{
[super viewDidLoad];
if (nil == xmlcont) {
xmlcont = [[XMLController alloc] loadXMLByURL:#"http://link_to_XML_file.xml"];
NSLog(#"array = %#", [xmlcont newsArray]);
for (myNews *oneNew in [xmlcont newsArray]) {
NSLog(#"URL = %#", [oneNew itemImageUrl]);
}
}
}
PS If you add this code and still get the output twice then you're making two versions of the ViewController.

Debugger message

I do webservice requests with a UISegmentedControl, when I change segmentedItem and request fast the application crashes with this message:
[Session started at 2011-05-12
10:58:50 +0200.] Terminating in
response to SpringBoard's termination.
[Session started at 2011-05-12
11:06:31 +0200.] GNU gdb
6.3.50-20050815 (Apple version gdb-1516) (Fri Feb 11 06:19:43 UTC
2011) Copyright 2004 Free Software
Foundation, Inc. GDB is free software,
covered by the GNU General Public
License, and you are welcome to change
it and/or distribute copies of it
under certain conditions. Type "show
copying" to see the conditions. There
is absolutely no warranty for GDB.
Type "show warranty" for details. This
GDB was configured as
"--host=i386-apple-darwin
--target=arm-apple-darwin".tty /dev/ttys001 Loading program into
debugger… Program loaded. target
remote-mobile
/tmp/.XcodeGDBRemote-239-58 Switching
to remote-macosx protocol mem 0x1000
0x3fffffff cache mem 0x40000000
0xffffffff none mem 0x00000000 0x0fff
none run Running… [Switching to thread
11779] [Switching to thread 11779]
sharedlibrary apply-load-rules all
continue Program received signal:
“SIGKILL”. warning: Unable to read
symbols for
/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3
(8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib
(file not found). kill quit
The Debugger has exited with status
0.(gdb)
Does anybody have an idea of how can I fix this?
Is this a problem because I'm not using NSOperationQueue?
And if so any suggestions how I can fix this would be very welcomed.
I can not find any memory leaks when running.
Next time I ran it this message got logged:
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3 (8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb)
Here is the code for starting the connection:
Class header ServiceGetChildren:
#import <Foundation/Foundation.h>
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
Authentication *authentication;
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
}
#property (nonatomic, retain) NSString *username;
#property (nonatomic, retain) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, retain) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Class handling the request:
#import "ServiceGetChildren.h"
#import "JSON.h"
#import "Base64.h"
#import "AttendanceReportViewController.h"
#import "Authentication.h"
#implementation ServiceGetChildren
#synthesize appDelegate;
#synthesize username;
#synthesize password;
#synthesize authenticationString;
#synthesize encodedLoginData;
#synthesize responseData;
#synthesize childrensArray;
- (id) init {
if ((self = [super init])) {
}
return self;
}
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller {
username = appDelegate.username;
password = appDelegate.password;
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", username, password];
encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if(connection) {
NSLog(#"Connection made");
responseData = [[NSMutableData data] retain];
}
else {
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Connection finished loading.");
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
NSMutableArray *array = [jsonData objectForKey:#"Children"];
childrensArray = [NSMutableArray arrayWithArray:array];
// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];
[connection release];
[responseData release];
[jsonString release];
[parser release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failure.");
NSLog(#"ERROR%#", error);
// Dismiss the network indicator when connection failure occurred
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
// Inform the user that the server was unavailable
}
- (void) dealloc {
[attendanceReportViewController release];
[super dealloc];
}
Class header for AttendanceReportViewController:
#import <UIKit/UIKit.h>
#class ServiceGetGroups;
#class ServiceGetChildren;
#class DetailViewController;
#interface AttendanceReportViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
ServiceGetGroups *serviceGetGroups;
ServiceGetChildren *serviceGetChildren;
DetailViewController *detailViewController;
UISegmentedControl *segmentedControl;
IBOutlet UIToolbar *groupsToolbar;
NSMutableArray *btnArray;
NSInteger index;
IBOutlet UITableView *theTableView;
IBOutlet UILabel *attendanceLabel;
IBOutlet UILabel *abscentLabel;
IBOutlet UILabel *totalLabel;
NSMutableDictionary *selectRequestDictionary;
NSMutableDictionary *selectNameDictionary;
NSMutableArray *groupsArray;
NSMutableArray *childrensArray;
NSDictionary *childrensDictionary;
NSURL *url;
}
#property (nonatomic, retain) ServiceGetGroups *serviceGetGroups;
#property (nonatomic, retain) ServiceGetChildren *serviceGetChildren;
#property (nonatomic, retain) DetailViewController *detailViewController;
#property (nonatomic, retain) IBOutlet UIToolbar *groupsToolbar;
#property (nonatomic, retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) IBOutlet UILabel *attendanceLabel;
#property (nonatomic, retain) IBOutlet UILabel *abscentLabel;
#property (nonatomic, retain) IBOutlet UILabel *totalLabel;
#property (nonatomic, retain) UISegmentedControl *segmentedControl;
#property (nonatomic) NSInteger index;
#property (nonatomic, retain) NSMutableArray *btnArray;
#property (nonatomic, retain) NSMutableDictionary *selectRequestDictionary;
#property (nonatomic, retain) NSMutableDictionary *selectNameDictionary;
#property (nonatomic, retain) NSMutableArray *groupsArray;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSDictionary *childrensDictionary;
#property (nonatomic, retain) NSURL *url;
- (void)setupSegmentedControl;
- (void)requestGroups;
- (void)requestChildren:(NSNumber *)groupId;
- (void)loadGroups;
- (void)loadChildren;
#end
Class that the Uses the UISegmentedControl:
#import "JSON.h"
#import "AttendanceReportViewController.h"
#import "CustomCellViewController.h"
#import "DetailViewController.h"
#import "ServiceGetGroups.h"
#import "ServiceGetChildren.h"
#import "Group.h"
#import "Child.h"
#implementation AttendanceReportViewController
#synthesize serviceGetGroups;
#synthesize serviceGetChildren;
#synthesize detailViewController;
#synthesize segmentedControl;
#synthesize groupsToolbar;
#synthesize index;
#synthesize btnArray;
#synthesize theTableView;
#synthesize attendanceLabel;
#synthesize abscentLabel;
#synthesize totalLabel;
#synthesize selectRequestDictionary;
#synthesize selectNameDictionary;
#synthesize groupsArray;
#synthesize childrensArray;
#synthesize childrensDictionary;
#synthesize url;
#pragma mark -
#pragma mark View lifecycle
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
- (void)requestGroups {
NSURL *groupsURL = [NSURL URLWithString:#"http://services/groups"];
[serviceGetGroups startService:groupsURL :#"GET" withParent:self];
}
- (void)requestChildren:(NSNumber *)groupId {
NSLog(#"%#", groupId);
NSString *baseURL = #"http://services/group/";
NSString *method = [NSString stringWithFormat:#"%#%#", groupId, #"/children"];
NSString *theURL = [NSString stringWithFormat:#"%#%#", baseURL, method];
self.url = [NSURL URLWithString:theURL];
NSLog(#"%#", self.url);
[serviceGetChildren startService:self.url :#"GET" withParent:self];
}
- (void)loadGroups {
// Retrieve a array with dictionaries of groups from ServiceGetGroups
self.groupsArray = [[serviceGetGroups.groupsArray copy] autorelease];
// The array to hold segmentedItems for the segmentedControl, representing groups buttons
btnArray = [NSMutableArray arrayWithObjects: #"Alla", nil];
for (NSDictionary *groupDict in groupsArray) {
// Add each groups name to the btnArray as segmentedItems for the segmentedControl
[btnArray addObject:[groupDict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group names as keys and group id´s as values
// used for reference to segementedControl items to make request to serviceGetChildren
self.selectRequestDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectRequestDictionary setObject:[dict objectForKey:#"Id"] forKey:[dict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group id´s as keys and group names as values
// used for retrieving a groupName from a passed id
self.selectNameDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectNameDictionary setObject:[dict objectForKey:#"Name"] forKey:[dict objectForKey:#"Id"]];
}
[self setupSegmentedControl];
}
- (void)setupSegmentedControl {
// Setup the UISegmentedControl as groups buttons
segmentedControl = nil;
segmentedControl = [[UISegmentedControl alloc] initWithItems:btnArray];
segmentedControl.tintColor = [UIColor darkGrayColor];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 300, 30);
// Setup the target and actions for the segmentedControl
[segmentedControl addTarget:self
action:#selector(selectGroup:)
forControlEvents:UIControlEventValueChanged];
// Add the UISegmentedControl as a UIBarButtonItem subview to the UIToolbar
UIBarButtonItem *segmentedItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *groupsButtons = [NSArray arrayWithObjects:flexSpace, segmentedItem, flexSpace, nil];
[groupsToolbar setItems:groupsButtons];
[flexSpace release];
}
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
// TODO create seperate method - Setup compilation bar values
int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:#"%d", total];
[theTableView reloadData];
}
// Handles UIControlEventValueChanged for UISegmentedControl, retreives the name and id for a selected group
- (void)selectGroup:(UISegmentedControl *)theSegmentedControl {
NSString *selectedGroup = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
NSNumber *selectedId = [selectRequestDictionary objectForKey:selectedGroup];
// Persist the selectedSegmentIndex when view switches to detaildView
index = [segmentedControl selectedSegmentIndex];
// Request children based on the selected groupId
[self requestChildren:selectedId];
}
- (void)viewDidLoad {
[self requestGroups];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [childrensArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
// Load from nib
CustomCellViewController *cell = (CustomCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"CustomCellView"
owner:nil
options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCellViewController *) currentObject;
break;
}
}
}
// Set up a children dictionary for easy retrieving specific values to display in the UITableView
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *name = [NSString stringWithFormat:#"%# %#",
[childrensDictionary valueForKey:#"Firstname"],
[childrensDictionary valueForKey:#"Surname"]];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
cell.childNameLabel.text = name;
cell.groupNameLabel.text = group;
cell.scheduleLabel.text = #"Schema";
cell.deviationLabel.text = #"Avvikelse";
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push the detailedViewController.
if (detailViewController == nil) {
DetailViewController *_detailViewcontroller = [[DetailViewController alloc]
initWithNibName:#"DetailView" bundle:nil];
self.detailViewController = _detailViewcontroller;
[_detailViewcontroller release];
}
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
[self.detailViewController initWithDetailsSelected:childrensDictionary:group];
[self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
segmentedControl = nil;
}
- (void)dealloc {
[segmentedControl release];
[groupsArray release];
[childrensArray release];
[detailViewController release];
[super dealloc];
}
#end
OK here we go. First of all, I could not test the code, so I need your feedback.
The main problem with this class is, you only have one instance, which you reuse every time you hit the segmented control. This leads to creation of new instances of the NSURLConnection. So let's correct a bit in the header. I changed the NSString properties to copy. Have a look at this Q&A to know why, however this is not important for the improvement, just wanted to let you know.
I've removed Authentication *authentication; looked like you don't use it.
Added NSURLConnection as property so we keep a reference on it.
Header file
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
NSURLConnection *connection;
}
#property (nonatomic, copy) NSString *username;
#property (nonatomic, copy) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, copy) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSURLConnection *connection
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Next comes the Implementation file. I only altered the startService method and dealloc.
If you declare properties, use them :) Have a look at this Q&A for some explanations on synthesized properties.
Always release what you own, so I added release code in the dealloc.
Cancel the previous request!!! If there is none, the message is sent to nil, which causes no harm.
Implementation file
- (void)startService:(NSURL *)url:(NSString *)method withParent:(UIViewController *)controller
{
self.username = appDelegate.username;
self.password = appDelegate.password;
[connection cancel];
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString *)[#"" stringByAppendingFormat:#"%#:%#", username, password];
self.encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if (connection) {
NSLog(#"Connection made");
self.responseData = [NSMutableData data];
} else {
NSLog(#"Connection could not be made");
}
}
...
- (void) dealloc
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection cancel];
[connection release];
[appDelegate release];
[responseData release];
[username release];
[password release];
[authenticationString release];
[encodedLoginData release];
[responseData release];
[childrensArray release];
[super dealloc];
}
Hope this helps for the next steps. However I think we will have to work a bit on the solution until it's final.

NSXMLParser values not being retained

This is similar to my previous question. I didn't get an answer, maybe by changing the question I might get an answer.
Here is my parsing code:
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *) namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict
{
if ([elementName isEqualToString:kimgurl]
|| [elementName isEqualToString:kone_x]
|| [elementName isEqualToString:kone_y]
|| [elementName isEqualToString:kone_radius]
|| [elementName isEqualToString:ktwo_x]
|| [elementName isEqualToString:ktwo_y]
|| [elementName isEqualToString:ktwo_radius])
{
elementFound = YES;
theItems = [[Items alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:kimgurl])
{
theItems.imageURL = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:kone_x])
{
theItems.iOne_X = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:kone_y])
{
theItems.iOne_Y = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:kone_radius])
{
theItems.iOne_Radius = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:ktwo_x])
{
theItems.iTwo_X = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:ktwo_y])
{
theItems.iTwo_Y = self.currentValue;
[self.currentValue setString:#""];
}
else if([elementName isEqualToString:ktwo_radius])
{
theItems.iTwo_Radius = self.currentValue;
[self.currentValue setString:#""];
}
}
-(void) parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"enddocument: %#", theItems.imageURL);
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
if (elementFound == YES) {
if(!currentValue)
{
currentValue = [NSMutableString string];
}
[currentValue appendString: string];
}
}
When I get to parserDidEndDocument. The theItems class is empty.
Here is Items.h
#import <Foundation/Foundation.h>
#interface Items : NSObject {
#private
//parsed data
NSString *imageURL;
NSString *iOne_X;
NSString *iOne_Y;
NSString *iOne_Radius;
NSString *iTwo_X;
NSString *iTwo_Y;
NSString *iTwo_Radius;
}
#property (nonatomic, retain) NSString *imageURL;
#property (nonatomic, retain) NSString *iOne_X;
#property (nonatomic, retain) NSString *iOne_Y;
#property (nonatomic, retain) NSString *iOne_Radius;
#property (nonatomic, retain) NSString *iTwo_X;
#property (nonatomic, retain) NSString *iTwo_Y;
#property (nonatomic, retain) NSString *iTwo_Radius;
#end
here is Items.m
#import "Items.h"
#implementation Items
#synthesize imageURL;
#synthesize iOne_X;
#synthesize iOne_Y;
#synthesize iOne_Radius;
#synthesize iTwo_X;
#synthesize iTwo_Y;
#synthesize iTwo_Radius;
-(void)dealloc
{
[imageURL release];
[iOne_X release];
[iOne_Y release];
[iOne_Radius release];
[iTwo_X release];
[iTwo_Y release];
[iTwo_Radius release];
[super dealloc];
}
#end
here is my RootViewController.h
#import <UIKit/UIKit.h>
#class Items;
#interface RootViewController : UIViewController <NSXMLParserDelegate> {
NSMutableData *downloadData;
NSURLConnection *connection;
BOOL elementFound;
NSMutableString *currentValue;
NSMutableDictionary *pictures;
//---xml parsing---
NSXMLParser *xmlParser;
Items *theItems;
NSMutableArray *aItems;
}
#property (nonatomic, retain) Items *theItems;
#property (nonatomic, retain) NSMutableArray *aItems;
#property (nonatomic, retain) NSMutableString *currentValue;
#property (nonatomic, retain) NSMutableData *downloadData;
#property (nonatomic, retain) NSURLConnection *connection;
#end
xml file example
<?xml version="1.0" encoding="utf-8"?>
<data>
<test>
<url>url</url>
<one_x>83</one_x>
<one_y>187</one_y>
<one_radius>80</one_radius>
<two_x>183</two_x>
<two_y>193</two_y>
<two_radius>76</two_radius>
</test>
</data>
It looks like there are a couple of potential problems. In your didStartElement method you are alloc/init'ing a new Items object for every element and overwriting your previous one. Perhaps you can move the Items init into your –parserDidStartDocument: method. When you init, it should also look more like this:
Items *items = [[Items alloc] init];
self.theItems = items;
[items release];
Then you'll have the correct retain count when you are done.
I'd also recommend changing your NSString #property declarations to be copy instead of retain. The code:
theItems.imageURL = self.currentValue;
[self.currentValue setString:#""];
... isn't doing what you think. theItems.imageURL is going to be pointing at your NSMutableString and then you clear the mutable string right after which means imageURL is pointing at an empty mutable string. Then after all of the other iterations, all of them are pointing at the same NSMutableString which is empty. If you change the #property declarations to copy, then it'll set imageURL to an immutable NSString copy of the contents of self.currentValue.