Parsing method was not called in NSXML parser - iphone

I was using NSXML parser for parsing but it was not calling the parser delegate methods, its shows zero error but i don't know where i made a mistake. and i need to parse attribute contents also.
Thanks in advance
Here is my xml file and code
**1.
xml file
** <ROOT_ELEMENT><RESPONSE READ_TAG="LEVEL_LIST" RESULT="" TEXT=""/><USER USER_NAME="newadmin01" TOKEN_ID="0.6864221651800831" FULL_NAME="newadmin01, newadmin01"/><DATETIME UNFORMATTED_TEXT="Aug 10 2011 5:23PM" FORMATTED_TEXT="10 Aug 17:23"/><BREADCRUMB/><LEVEL_LIST><LEVEL ID="4519" NAME="Mega Mart" CHILD_EXISTS="Y" ADD_EDIT_PRIVILEGE="Y"/></LEVEL_LIST></ROOT_ELEMENT>
**2.
.h file
**
#interface MainLevelList : UIViewController
<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UISearchBarDelegate, NSXMLParserDelegate> {
UITableView *theTableView;
UILabel *lbl_title;
UILabel *lbl_time;
NSMutableArray *mainLevelListArray;
NSXMLParser *parser;
NSMutableString *elemName;
NSMutableString *currentValueString;
}
#property (nonatomic,retain) IBOutlet UILabel *lbl_title;
#property (nonatomic,retain) IBOutlet UILabel *lbl_time;
#property (nonatomic,retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) NSMutableArray *mainLevelListArray;
- (IBAction)onClickLeftArrow;
- (IBAction)onClickRightArrow;
#end
**
- **3. .m file
**
#implementation MainLevelList
#synthesize mainLevelListArray;
#synthesize theTableView;
#synthesize lbl_title;
#synthesize lbl_time;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:#"answerBtn.png"] forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(0, 0, 66, 34)];
[button1 addTarget:self action:#selector(answerBtn:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:#"Answer" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button1];
NSMutableArray *toolBarItems = [[[NSMutableArray alloc] init] autorelease];
[toolBarItems addObject:barButtonItem];
//[self setToolbarItems:toolBarItems];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button3 setFrame:CGRectMake(150, 0, 66, 34)];
[button3 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button3 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button3];
[toolBarItems addObject:barButtonItem2];
button3.hidden = YES;
//[self setToolbarItems:toolBarItems];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button4 setFrame:CGRectMake(200, 0, 66, 34)];
[button4 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button4];
[toolBarItems addObject:barButtonItem3];
button4.hidden = YES;
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:#"nextBtn.png"] forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(250, 0, 66, 34)];
[button2 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:#"Next" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:button2];
[toolBarItems addObject:barButtonItem1];
[self setToolbarItems:toolBarItems];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *responseXml = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] valueForKey:#"responseXml"]];
//[[NSUserDefaults standardUserDefaults] setObject:responseXml forKey:#"responseXml"];
parser = [[NSXMLParser alloc] initWithData:[responseXml dataUsingEncoding:NSUTF8StringEncoding]];
[responseXml release];
[parser setDelegate:self];
BOOL parseFlag = [parser parse];
if (parseFlag == 1)
if(debug)NSLog(#"parseFlag = YES");
else
if(debug)NSLog(#"parseFlag = NO");
UINavigationBar *bar = [self.navigationController navigationBar];
CGRect labelRect = CGRectMake(255, 12, 60, 18);
UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
[bar addSubview:label];
label.text = #"ALRICK";
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont boldSystemFontOfSize:14];
label.tag = 10;
[label release];
UIButton *logOutButton = [UIButton buttonWithType:100];
[logOutButton setImage:[UIImage imageNamed:#"exitBtn.png"] forState:UIControlStateNormal];
[logOutButton addTarget:self action:#selector(logoutButtonTouched) forControlEvents:UIControlEventTouchUpInside];
[logOutButton setTitle:#"Logout" forState:UIControlStateNormal];
UIBarButtonItem* logOutItem = [[UIBarButtonItem alloc] initWithCustomView:logOutButton];
self.navigationItem.leftBarButtonItem = logOutItem;
[lbl_title setText:#"Chain"];
[lbl_title setTextColor:[UIColor whiteColor]];
NSString *date = [NSDate date];
//NSString *date = [[NSDate date] initWithFormat:#"EEE, MMM, h:mm"];
NSLog(#"date:%#",date);
[lbl_time setText:[NSString stringWithFormat:#"%#",date]];
[lbl_time setTextColor:[UIColor whiteColor]];
mainLevelListArray = [[NSMutableArray alloc] init];
//[tableData addObject:#"ICA"];
// [tableData addObject:#"Bread"];
// [tableData addObject:#"ISF"];
// [tableData addObject:#"OSF"];
// [tableData addObject:#"BBC"];
// [tableData addObject:#"ACC"];
// [tableData addObject:#"CFF"];
}
-(void)answerBtn:(id)sender {
QuestionnaireListView *m_questionnaireList = [[QuestionnaireListView alloc] initWithNibName:#"QuestionnaireListView" bundle:nil];
[self.navigationController pushViewController:m_questionnaireList animated:YES];
[m_questionnaireList release];
}
- (void)logoutButtonTouched {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickLeftArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickRightArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
[mainLevelListArray release];
}
#pragma mark - UITableView delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [mainLevelListArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [mainLevelListArray objectAtIndex:indexPath.row];
UIView *m_view = [[[UIView alloc] init] autorelease];
m_view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"listHighlight_bg.png"]];
cell.selectedBackgroundView = m_view;
return cell;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
NSLog(#"element Name = %#", elementName);
NSLog(#"namespace URI = %#", namespaceURI);
NSLog(#"qualified Name = %#", qName);
NSLog(#"attributeDict = %#", attributeDict);
elemName = [[NSString alloc] initWithString:elementName];
attributeDict = [[NSString alloc] initWithString:[attributeDict objectForKey:#"READ_TAG"]];
//attribute = [attributeDict objectForKey:#"READ_TAG"];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([elemName isEqualToString:#"RESPONSE"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"USER"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
if ([elemName isEqualToString:#"DATETIME"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"LEVEL"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elemName isEqualToString:#"RESPONSE"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"USER"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"DATETIME"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"LEVEL"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
}
#end
**

add few lines in viewDidLoad method as given below
(void)viewDidLoad {
[super viewDidLoad];
//NSMutableString *urlString ; //assign url string
NSString *postLength = [NSString stringWithFormat:#"%d", [urlString length]];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[urlString dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//write your rest part of viewDidLoad
}

Please check the encoding scheme in xml which you are getting from server side as a response and check your iPhone client code it's UTF8, UTF16 or something else.

Related

ImageGallery image in black for ios 7

In my efforts to upgrade my application to support IOS7 I found out that ImageGallery don't load the images. in others iOS is ok.
In imageGalleryView:
- (void)initWithPhotos:(NSMutableArray *)photoURLStrings andCaptions:(NSArray *)myCaptions moveToPage:(int)page {
captions = [myCaptions copy];
photoUrls = [photoURLStrings copy];
NSLog(#"array---> %#", photoUrls);
photoLoaded = [[NSMutableArray alloc] init];
for (int i=0; i<[photoURLStrings count]; i++) {
[photoLoaded addObject:[NSNumber numberWithBool:FALSE]];
}
[pageControl setNumberOfPages:[photoUrls count]];
//scrollView= [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor blackColor];
scrollView.pagingEnabled = TRUE;
scrollView.autoresizesSubviews = TRUE;
scrollView.contentSize = CGSizeMake(320 * [photoUrls count], scrollView.frame.size.height);
scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width*page, 0);
if (([captions objectAtIndex:page] == nil) || ([[captions objectAtIndex:page] isEqualToString:#""])) {
[textView setHidden:TRUE];
} else {
[textView setHidden:FALSE];
[textView setText:[captions objectAtIndex:page]];
}
[self showImages:page];}
- (void)showImages:(int)page {
AsyncImageViewController *asyncImageView;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
//NSLog(#"%#",[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]);
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
//NSLog(#"page:%i",page);
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page - 1;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page + 2;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[asyncImageView release];}}}
In the asyncimageview:
- (void)loadImageFromURL:(NSURL*)url pos:(int) posicio {
if (connection!=nil) { [connection release]; }
if (data!=nil) { [data release]; }
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
if (posicio == 0) {
loading.center = CGPointMake(75/2,75/2);
}else {
loading.center = CGPointMake(160,210);
}
[loading startAnimating];
[self addSubview:loading];
[loading release];}//the URL connection calls this repeatedly as data arrives- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
[data appendData:incrementalData];}//the URL connection calls this once all the data has downloaded- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//so self data now has the complete image
[connection release];
connection=nil;
if ([[self subviews] count]>0) {
//then this must be another image, the old one is still in subviews
[[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
}//make an image view for the image
imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
//make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
//[self setBackgroundColor:[UIColor colorWithPatternImage:imageView]];
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[loading stopAnimating];
[data release]; //don't need this any more, its in the UIImageView now
data=nil;}
//just in case you want to get the image directly, here it is in subviews- (UIImage*) image {
UIImageView* iv = [[self subviews] objectAtIndex:0];
return [iv image];}
I checked all and saw that it is UIView instead of UIImageView. probably Apple changed something. But xCode don't throw any errors.
Any idea how to fix it?

Replacing Not adding: UICollectionView

I am creating a client app for Instagram the gets pictures, however when the user gets to the bottom of the page it is is supposed to bring a new group of uicollectionviewcell's however it replaces the existing ones and i cannot see them anymore unless i refresh. All the nessecary code is provided below, thanks for your help in advance:
#interface StreamViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
#property (nonatomic, strong) NSMutableDictionary *timelineResponse;
#property (nonatomic, strong) CredentialStore *credentialStore;
#property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
#end
#implementation StreamViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self refreshInstagram];
//Refresh
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(startRefresh:)
forControlEvents:UIControlEventValueChanged];
[self.collectionView addSubview:refreshControl];
//Instigate Navigation Bar Buttons
UIButton *barButton = [UIButton buttonWithType:UIButtonTypeCustom];
[barButton setTitle:#"" forState:UIControlStateNormal];
[barButton setBackgroundImage:[UIImage imageNamed:#"barButton.png"] forState:UIControlStateNormal];
[barButton setBackgroundImage:[UIImage imageNamed:#"barButton_s.png"] forState:UIControlStateHighlighted];
[barButton addTarget:self action:#selector(didTapBarButton:) forControlEvents:UIControlEventTouchUpInside];
barButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:barButton];
self.navBar.leftBarButtonItem = barButtonItem;
UIButton *postButton = [UIButton buttonWithType:UIButtonTypeCustom];
[postButton setTitle:#"" forState:UIControlStateNormal];
[postButton setBackgroundImage:[UIImage imageNamed:#"pen_usIMG.png"] forState:UIControlStateNormal];
[postButton setBackgroundImage:[UIImage imageNamed:#"pen_sIMG.png"] forState:UIControlStateHighlighted];
[postButton addTarget:self action:#selector(didTapPostButton:) forControlEvents:UIControlEventTouchUpInside];
postButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
UIBarButtonItem *postButtonItem = [[UIBarButtonItem alloc] initWithCustomView:postButton];
self.navBar.rightBarButtonItem = postButtonItem;
//Reload by default
[self.collectionView reloadData];
}
//Global refresh Instagram Method
- (void)refreshInstagram {
[[InstagramClient sharedClient] getPath:#"users/self/feed"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
self.timelineResponse = [responseObject mutableCopy];
[self.collectionView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
- (void)nextInstagramPage:(NSIndexPath *)indexPath{
NSDictionary *page = self.timelineResponse[#"pagination"];
NSString *nextPage = page[#"next_url"];
[[InstagramClient sharedClient] getPath:[NSString stringWithFormat:#"%#",nextPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.timelineResponse = [responseObject mutableCopy];
[self.timelineResponse addEntriesFromDictionary:responseObject];
[self.collectionView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
- (NSMutableArray *)entries {
return self.timelineResponse[#"data"];
}
- (NSArray *)pages {
return self.timelineResponse[#"pagination"];
}
- (NSURL *)imageUrlForEntryAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *entry = [self entries][indexPath.row];
NSString *imageUrlString = entry[#"images"][#"standard_resolution"][#"url"];
return [NSURL URLWithString:imageUrlString];
}
#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//int y = arc4random() % 200+50;
return CGSizeMake(150, 150);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Item Tapped!" message:#"Thank God its working"];
[modal show];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y == roundf(scrollView.contentSize.height-scrollView.frame.size.height)) {
NSLog(#"we are at the endddd");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self nextInstagramPage:indexPath];
}
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[self entries] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ImageCell *cell = (ImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"imageCell"
forIndexPath:indexPath];
NSURL *url = [self imageUrlForEntryAtIndexPath:indexPath];
NSLog(#"%#", url);
[cell.imageView setImageWithURL:url];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
#pragma mark - NavigationBarButtons
- (void)didTapBarButton:(id)sender {
[self.sidePanelController showLeftPanelAnimated:YES];
}
- (void)startRefresh:(UIRefreshControl *)sender {
[self refreshInstagram];
[sender endRefreshing];
}
-(void)didTapPostButton:(id)sender {
}
#end
Your problem is probably arising from this line:
self.timelineResponse = [responseObject mutableCopy];
At this point, all the objects in timelineResponse are deleted. Try removing this line and I bet you'll be fine.

Search Bar doesn't work on Device in ios

I created iOS(5.0) application in that I have search Bar, which is used to search the content in server side, while passing keyword entered into search bar the list of content parsed from the xml and shown in Table View,
its working fine in Emulator,.but in device (ipad2 & iphone4s) its not showing table of content were searched.
pls let me know what am making wrong..
Thanks in advance,.
murali.
This is mySearchClass.h
#interface SearchClass : UIViewController<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate,UISearchBarDelegate, UISearchDisplayDelegate>
{
AppDelegate *abc;
MBProgressHUD *HUD;
IBOutlet UIScrollView *scrv;
IBOutlet UITableView *tableV;
UISearchBar *searchBar;
IBOutlet UILabel *lblTitle;
IBOutlet UIActionSheet *actionSheet;
IBOutlet UIPickerView *pickerView;
IBOutlet UIButton *btnActionSheet;
UIToolbar *pickerToolBar;
NSMutableArray *arrCate;
NSString *key;
}
-(void)cleartable;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
#end
//======================
This is my SearchClass.m
#implementation SearchClass
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.image = [UIImage imageNamed:#"search"];
UIImageView *navImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"i-street"]];
self.navigationItem.titleView = navImg;
}
return self;
}
- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg1.png"]];
abc = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//[SearchClass initWithNibName:#"" bundle:nil];
//[SearchClass initWithNibName:#"SearchClass" bundle:nil];
arrCate = [[NSMutableArray alloc]initWithObjects:#"Arts & Entertainment",#"Restaurants",#"Bars, Pubs & Clubs",#"Film and Cinema",#"Live Gigs",#"Shops", nil];
pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 43 , 320, 480)];
pickerView.delegate = self;
pickerView.dataSource = self;
[pickerView setShowsSelectionIndicator:YES];
pickerToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
pickerToolBar.barStyle = UIBarStyleBlackOpaque;
[pickerToolBar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIButton *btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDone setFrame:CGRectMake(0, 0, 60, 30)];
[btnDone addTarget:self action:#selector(closeActionSheet) forControlEvents:UIControlEventTouchUpInside];
[btnDone setBackgroundImage:[UIImage imageNamed:#"done.png"] forState:UIControlStateNormal];
UIBarButtonItem *dbtn = [[UIBarButtonItem alloc]initWithCustomView:btnDone];
[barItems addObject:dbtn];
[pickerToolBar setItems:barItems animated:YES];
}
-(IBAction)closeActionSheet
{
lblTitle.text=[arrCate objectAtIndex:[pickerView selectedRowInComponent:0]];
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [arrCate objectAtIndex:row];
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
return [arrCate count];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
lblTitle.text = [arrCate objectAtIndex:row];
[abc.arrSearch removeAllObjects];
[tableV reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// NSLog(#"table view count seasrch :%d",[abc.arrSearch count]);
return [abc.arrSearch count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *imgUrl;
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if(indexPath.row > 0)
{
UIImageView *separator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"line1.png"]];
[cell.contentView addSubview: separator];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgbest=[[UIImageView alloc]initWithFrame:CGRectMake(213,4,107,64)];
UIActivityIndicatorView *actSpiner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
actSpiner.center = imgbest.center;
[actSpiner startAnimating];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 200, 20)];
lbl.textAlignment = UITextAlignmentLeft;
lbl.font = [UIFont fontWithName:#"Helvetica" size:18.0];
lbl.textColor = [UIColor whiteColor];
lbl.backgroundColor = [UIColor clearColor];
lbl.numberOfLines=0;
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 23, 200, 20)];
lbl1.textAlignment = UITextAlignmentLeft;
lbl1.font = [UIFont fontWithName:#"American Typewriter" size:13.0];
lbl1.textColor = [UIColor whiteColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.numberOfLines=0;
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(5,44, 200, 20)];
lbl2.textAlignment = UITextAlignmentLeft;
lbl2.font = [UIFont fontWithName:#"Helvetica-Oblique" size:12.0];
lbl2.textColor = [UIColor whiteColor];
lbl2.backgroundColor = [UIColor clearColor];
lbl2.numberOfLines=0;
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
ArtsClass *arts=[[ArtsClass alloc]init];
arts = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = arts.artThumpImg;
lbl.text=arts.artTitle;
lbl1.text=arts.artDesc;
lbl2.text=arts.artDate;
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
ResClass *res=[[ResClass alloc]init];
res = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = res.resLogoImg;
lbl.text=res.resName;
lbl1.text=res.resType;
lbl2.text=res.resPopularDish;
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
BarClass *bar=[[BarClass alloc]init];
bar = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = bar.barImg;
lbl.text=bar.barTitle;
lbl1.text=bar.barDesc;
lbl2.text=bar.barFacilities;
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
FilmClass *film=[[FilmClass alloc]init];
film = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = film.filmImg;
lbl.text=film.filmName;
lbl1.text=film.filmSynopsis;
lbl2.text=film.filmReleDate;
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
GigsClass *gigs=[[GigsClass alloc]init];
gigs = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = gigs.eventThumpImg;
lbl.text=gigs.eventTitle;
lbl1.text=gigs.eventCate;
lbl2.text=[NSString stringWithFormat:#"%# - %#",gigs.eventStartDate,gigs.eventEndDate];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
ShopsClass *shops=[[ShopsClass alloc]init];
shops = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = shops.shopThumpImg;
lbl.text=shops.shopName;
lbl1.text=shops.shopDesc;
lbl2.text=shops.shopFacilities;
}
NSURL *url = [NSURL URLWithString:imgUrl] ;
// NSLog(#"image link:%#",url);
dispatch_queue_t currQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(currQueue,^{
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
imgbest.image = [UIImage imageWithData:data];
});
});
[cell addSubview:actSpiner];
[cell addSubview:imgbest];
[cell addSubview:lbl];
[cell addSubview:lbl1];
[cell addSubview:lbl2];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
abc.subClassTag=#"ARTS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Arts & Entertainment";
abc.objArt = [abc.arrArts objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
abc.subClassTag=#"RES";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Restaurants";
abc.objRest = [abc.arrRes objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
abc.subClassTag=#"BAR";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Bars, Pubs & Clubs";
abc.objBar = [abc.arrBars objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
abc.subClassTag=#"FILMS";
abc.classTag = #"PLAYERCLASS";
abc.strTitle = #"Film and Cinema";
abc.objFilm = [abc.arrFilm objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
abc.subClassTag=#"GIGS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Live Gigs";
abc.objGig = [abc.arrGigs objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
abc.subClassTag=#"SHOPS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Shops";
abc.objShop = [abc.arrShops objectAtIndex:indexPath.row];
}
if([abc.classTag isEqualToString:#"PLAYERCLASS"])
{
PlayerClass *pl = [[PlayerClass alloc]init];
[self.navigationController pushViewController:pl animated:YES];
}
else if([abc.classTag isEqualToString:#"GALLERYCLASS"])
{
GalaryClass *gc = [[GalaryClass alloc]init];
[self.navigationController pushViewController:gc animated:YES];
}
}
- (void)viewDidUnload
{
scrv = nil;
tableV = nil;
searchBar = nil;
lblTitle = nil;
[super viewDidUnload];
}
-(IBAction)getCategory:(id)sender
{
[searchBar resignFirstResponder];
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil //#"Done"
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setTag:0];
[actionSheet addSubview:pickerView];
[actionSheet showInView:self.view.superview];
[actionSheet addSubview:pickerToolBar];
[actionSheet showInView:self.view.superview];
[actionSheet setBounds:CGRectMake(0, 0, 320, 430)];
}
-(void)cleartable
{
NSArray * ar=[tableV subviews];
for(int j=0;j<ar.count;j++)
{
NSArray *arr=[[ar objectAtIndex:j]subviews];
for(int i=0;i<arr.count;i++)
{
if([[arr objectAtIndex:i]isKindOfClass:[UILabel class]])
{
[[arr objectAtIndex:i]removeFromSuperview];
}
}
}
}
-(void)showProgress
{
//[searchBar resignFirstResponder];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
// Set the hud to display with a color
HUD.color = [UIColor colorWithPatternImage:[UIImage imageNamed:#"box4"]];//[UIColor colorWithRed:0.23 green:0.50 blue:0.82 alpha:0.90];
// HUD.opacity =
HUD.delegate = self;
[HUD showWhileExecuting:#selector(download) onTarget:self withObject:nil animated:YES];
}
-(void)download
{
if([NetworkManager checkForNetworkStatus])
{
ParserClass *p =[[ParserClass alloc]init];
NSLog(#"search bar text %# --- %#",key,lblTitle.text);
if (lblTitle.text==#"Arts & Entertainment")
{
[p search:1 string:key];
}else if(lblTitle.text==#"Restaurants")
{
[p search:5 string:key];
}else if(lblTitle.text==#"Bars, Pubs & Clubs")
{
[p search:4 string:key];
}else if(lblTitle.text==#"Film and Cinema")
{
[p search:2 string:key];
}else if(lblTitle.text==#"Live Gigs")
{
[p search:3 string:key];
}else if(lblTitle.text==#"Shops")
{
[p search:6 string:key];
}
[tableV reloadData];
}
else
{
UIAlertView *alrt = [[UIAlertView alloc]initWithTitle:#"Network Error!" message:#"Please Check your Network connetion.." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alrt show];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}
- (void)searchBar:(UISearchBar *)searchBar1 textDidChange:(NSString *)searchText
{
if(![lblTitle.text isEqualToString:#"Select Category"])
{
if(searchBar.text.length > 0)
{
key = searchText;
[self showProgress];
// ParserClass *p =[[ParserClass alloc]init];
// NSLog(#"search bar text %# --- %#",searchText,lblTitle.text);
// if (lblTitle.text==#"Arts & Entertainment")
// {
// [p search:1 string:searchText];
// }else if(lblTitle.text==#"Restaurants")
// {
// [p search:5 string:searchText];
// }else if(lblTitle.text==#"Bars, Pubs & Clubs")
// {
// [p search:4 string:searchText];
// }else if(lblTitle.text==#"Film and Cinema")
// {
// [p search:2 string:searchText];
// }else if(lblTitle.text==#"Live Gigs")
// {
// [p search:3 string:searchText];
// }else if(lblTitle.text==#"Shops")
// {
// [p search:6 string:searchText];
// }
//
// [tableV reloadData];
}
else
{
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:nil message:#"Please Give me some Key words..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert1 show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:#"Please Select any Category..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
#end
Thanks for ur Reply,.
Murali.
wrong string comparison
if (lblTitle.text==#"Arts & Entertainment")
it should be like this - try this it must work & let me know.
if (lblTitle.text isEqualToString:#"Arts & Entertainment")
I am also having some issues in my search class, i am using JSON url.
Where is the Parsing URL, what are the fields in the xml.
Check your parsing url in ur local browser by manual append method using query string ,working or not.
check by trace path, use console log for print the URL.
Check if u are using localhost url in ur program somewhere else.
Check your delegate for search class.
use this link for your reference.
https://iphonedevsdk.com/forum/iphone-sdk-development/50468-xml-table-view-searchbar.html

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil)
{
NSLog(#"Failed to parse %#", request.url);
}
else
{
NSMutableArray *entries = [NSMutableArray array];
[self parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property

AsyncImage get picture from program source?

from this code
#import "AsyncImageView.h"
#import "ImageCache.h"
#import "ImageCacheObject.h"
static ImageCache *imageCache = nil;
#implementation AsyncImageView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
- (void)dealloc {
[connection cancel];
[connection release];
[data release];
[super dealloc];
}
-(void)loadImageFromURL:(NSURL*)url {
if (connection != nil) {
[connection cancel];
[connection release];
connection = nil;
}
if (data != nil) {
[data release];
data = nil;
}
if (imageCache == nil)
imageCache = [[ImageCache alloc] initWithMaxSize:2*1024*1024];
[urlString release];
urlString = [[url absoluteString] copy];
UIImage *cachedImage = [imageCache imageForKey:urlString];
if (cachedImage != nil)
{ NSLog(#"get in");
if ([[self subviews] count] > 0)
{
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImageView *imageView = [[[UIImageView alloc] initWithImage:cachedImage] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
return;
}
#define SPINNY_TAG 5555
UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinny.tag = SPINNY_TAG;
spinny.center = self.center;
[spinny startAnimating];
[self addSubview:spinny];
[spinny release];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)incrementalData {
if (data==nil) {
data = [[NSMutableData alloc] initWithCapacity:2048];
}
[data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
[connection release];
connection = nil;
UIView *spinny = [self viewWithTag:SPINNY_TAG];
[spinny removeFromSuperview];
if ([[self subviews] count] > 0) {
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImage *image = [UIImage imageWithData:data];
[imageCache insertImage:image withSize:[data length] forKey:urlString];
UIImageView *imageView = [[[UIImageView alloc]
initWithImage:image] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout]; // is this necessary if superview gets setNeedsLayout?
[self setNeedsLayout];
[data release];
data = nil;
}
#end
If I wanna get picture from app source if url is empty , what code should I add ??
and here is more code from xyz.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
CellIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [self getCellContentView:CellIdentifier];
}
else{
AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
[oldImage removeFromSuperview];
}
int index = [indexPath indexAtPosition: [indexPath length] - 1];
//Get Picture
CGRect frame;
frame.size.width=50; frame.size.height=50;
frame.origin.x=10; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSString *string = [jsonPic objectAtIndex:index];
NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *imageURL = [NSURL URLWithString:url];
if([string isEqualToString:#""]){
NSLog(#"Not found");
at here I don't know How can I get picture from source
AsyncImageView * NoImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
NoImage.tag = 999;
NoImage.image = [UIImage imageNamed:#"bl-noImg.gif"];
[cell.contentView addSubview:NoImage];
}
else
{ NSLog(#"image URL %#",imageURL);
[asyncImage loadImageFromURL:imageURL];
[cell.contentView addSubview:asyncImage];
I can get picture from asyncImage
Please , Help me or guide me to do that. thank you
.
.
.
.
Now It's all done and here is my result code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
CellIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [self getCellContentView:CellIdentifier];
}
else{
AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
[oldImage removeFromSuperview];
}
int index = [indexPath indexAtPosition: [indexPath length] - 1];
//Get Picture
CGRect frame;
frame.size.width=50; frame.size.height=50;
frame.origin.x=10; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSString *string = [jsonPic objectAtIndex:index];
if([string isEqualToString:#""]){
//NSLog(#"Not found");
UIImageView * NoImg = [[[UIImageView alloc] initWithFrame:frame] autorelease];
NoImg.tag = 999;
[NoImg setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"bg-noImg" ofType:#"gif"]]];
[cell.contentView addSubview:NoImg];
}
else
{ //NSLog(#"image URL %#",imageURL);
NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *imageURL = [NSURL URLWithString:url];
[asyncImage loadImageFromURL:imageURL];
[cell.contentView addSubview:asyncImage];
}
thank you everyone : )
If you are checking for empty url then you should check it before calling to loadImageFromURL and even before creating NSURL object. If it is not empty then you should create NSURL object and call loadImageFromURL method.
somewhere in your code... from where you are calling loadImageFromURL:
if(urlString !=nil || [urlString length]>0)
{
create NSURL object
now again check NSURL object whether its nil or not
we are checking it because if the urlString has incorrect url pattern then no
NSURLObject would be created, so if there is no NSURLObject then we should not call
your method.
if(NSURLObject !=nil)
{
call loadImageFromURL method and so on
}
else
{
//load some default image. which will convey no URL Found
}
}
else
{
//load some default image. which will convey no URL Found
}
Thanks,