NSManagedObjectContext: From a UIViewController, how do you get the ManagedObjectContext in iOS? - ios

How do you know what the proper ManagedObjectContext is? Because I'm not in the appDelegate (where I think the code is) and I keep getting crashes in my app - specifically, in the 'ViewDidLoad' for MyTabBarViewController and the 'sendPressed' method for SecondViewController.
Could you tell me how to find the context? Because alloc init'ing my own context didn't work. Am I suppose to send a message to the appDelegate? I thought adding the appDelegate header file or calling it was the wrong thing to do.
SecondViewController.m
#import "SecondViewController.h"
#implementation SecondViewController
- (IBAction) sendPressed:(UIButton *)sender
{
for(UIViewController *controller in self.tabBarController.viewControllers)
{
if([controller isKindOfClass:[FirstViewController class]])
{
FirstViewController *fvc = (FirstViewController *)controller;
[fvc realLabel];
}
}
//add image to Core Data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:#"Photo" inManagedObjectContext:context];
photo.photo = imageData;
self.tabBarController.selectedIndex = 2;//switch over to the third view to see if it worked
}
...
#end
MyTabBarViewController.m
#import "MyTabBarViewController.h"
#implementation MyTabBarViewController
#synthesize pageControl,scroller;
-(IBAction)clickPageControl:(id)sender
{
int page=pageControl.currentPage;
CGRect frame=scroller.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scroller scrollRectToVisible:frame animated:YES];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x/scrollView.frame.size.width;
pageControl.currentPage=page;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
scroller.contentSize=CGSizeMake(pageControl.numberOfPages*scroller.frame.size.width, scroller.frame.size.height);
CGFloat scrollWidth = 0;
int pageNumber = 0;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
request.entity = [NSEntityDescription entityForName:#"Photo" inManagedObjectContext:context];
NSError *error = nil;
NSArray *fetchCount = [context executeFetchRequest:request error:&error];
int pageCount = [fetchCount count];
for (int i=0; i<pageCount; i++)
{
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
CGRect rect = scroller.frame;
rect.size.height = scroller.frame.size.height;
rect.size.width = scroller.frame.size.width;
rect.origin.x = scroller.frame.origin.x + scrollWidth;
rect.origin.y = scroller.frame.origin.y;
pvc.view.frame = rect;
[pvc view];
pvc.label.text = [NSString stringWithFormat:#"%d", pageNumber];
pvc.label.textColor = [UIColor redColor];
Photo *photo = [[Photo alloc] init];
photo = [fetchCount objectAtIndex:i];
UIImage *fetchedImage = [UIImage imageWithData:photo.photo];
pvc.imageView.image = fetchedImage;
[scroller addSubview:pvc.view];
[pvc release];
pageNumber++;
scrollWidth += scroller.frame.size.width;
}
pageControl.numberOfPages=pageCount;
pageControl.currentPage=0;
[self.view addSubview:scroller];
}
...
#end
If I import my CoreDataProjAppDelegate to each of these files and use NSManagedObjectContext *context = [(CoreDataProjAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; then it works fine. But is this the correct way?

You have to set the PersistentStoreCoordinator in order for the context to be valid:
NSPersistentStoreCoordinator *psc = ((CoreDataProjAppDelegate *)[UIApplication sharedApplication].delegate).persistentStoreCoordinator;
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:psc];
This is assuming you have a property on the app delegate named persistentStoreCoordinator which the default core data project will have. The psc is basically the link between your context (scratch pad) and your actual persistent storage (physical database).

Did you create your project with the "Use Core Data" box ticked? If you did that you'll have a managedObjectContext automatically, which you then pass to whatever other classes need it.

Related

Not able to scroll and select cells displayed in uisearch controller

I have a screen which shows favourite locations and if a user wants to add new location he can search using uisearchcontroller and add it to favourite location's list.
The problem is that once i make the api call for autocomplete the list of searched locations is visible but i cannot select or scroll the table.
I know that the problem is where i set the uisearchcontroller. but i do not know the right way to do it.
I am newbie in iOS so ur suggestions will be welcome.
the following is the GithubRepository for the project(incase ul want to try out the app and make suggestions)
and heres the related code where i beleive the problem exists.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
favList = [[NSMutableArray alloc] init];
searchList = [[NSMutableArray alloc]init];
self.table.dataSource = self;
self.table.delegate = self;
[self initSearch];
}
#pragma mark UI Search methods
-(void) initSearch
{
FavouriteViewController *searchResultsController = [[FavouriteViewController alloc] init];
searchResultsController.table.dataSource = self;
searchResultsController.table.delegate = self;
searchResultsController.table.allowsSelectionDuringEditing = YES;
searchResultsController.table.allowsSelection = YES;
self.search = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.definesPresentationContext = NO;
self.table.tableHeaderView = self.search.searchBar;
self.search.searchResultsUpdater = self;
self.search.searchBar.delegate = self;
self.search.dimsBackgroundDuringPresentation = NO;
}
didSelectRowAtIndex method
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.search.active) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObjectModel *place = [NSEntityDescription insertNewObjectForEntityForName:#"Place" inManagedObjectContext:context];
NSString *places =[searchList[indexPath.row] valueForKey:#"name"];
if (![favList containsObject:places])
{
NSString *lati = [searchList[indexPath.row] valueForKey:#"lat"];
NSString *longi = [searchList[indexPath.row] valueForKey:#"lon"];
if (places != NULL && lati != NULL && longi != NULL)
{
[place setValue:places forKey:#"placeName"];
[place setValue:lati forKey:#"latitude"];
[place setValue:longi forKey:#"longitude"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
[self.search setActive:NO];
filtered = NO;
[self getalldata];
[self.table reloadData];
}
else
{
NSManagedObject *device = [favList objectAtIndex:indexPath.row];
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:#"group.SJI.Weather-App"];
[defaults setObject:[device valueForKey:#"placeName"] forKey:#"favSet"];
[[self navigationController] popToRootViewControllerAnimated:YES];
}
}

convert parse to image in nsarray

Can anyone please help me here? scenario is:
I have a view controller, page view controller, and a content for page view controller.
The app is to initially load 3 pages of images, and on the 3rd page a button will then appear. if pressed it'll be directed to the main menu page.
all images are loaded from parse.
I previously had a separate program for page view controller and another for parse image loader, executed perfectly. however when I combine both together it fails. based on what I understand is that, images from parse are stored as NSData. however, in my page view controller, i'm using index to load the images. I tried converting NSData to NSArray using KeyedAchiver however it couldn't work.
I also notice that my image loaded from parse doesn't come in the sequence I want. So, if possible, please help to advise on this!
below are the codes. thanks in advance!
//***********************view controller
#import "ViewController.h"
#import <parse/parse.h>
#interface ViewController ()
#end
#implementation ViewController
#synthesize parseImageData,pageImages; //UIImage, NSData
- (void)viewDidLoad
{
[super viewDidLoad];
// Create the data model
// _pageTitles = #[#"New York Cheese", #"Vanilla Cake", #"Green Tea Cake", #"Choc Indulgence"];
// _pageImages = #[#"pic1.png", #"pic2.png", #"pic3.png", #"pic4.png"];
_pageTitles = #[#"New York Cheese", #"Vanilla Cake"];
// Create page view controller
self.pageViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"PageViewController"];
self.pageViewController.dataSource = self;
PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = #[startingViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
// Change the size of page view controller
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);
[self addChildViewController:_pageViewController];
[self.view addSubview:_pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
NSLog(#"viewcontroller.m viewdidload complete");
}
- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index
{
if (([self.pageTitles count] == 0) || (index >= [self.pageTitles count])) {
NSLog(#"out of range!");
return nil;
}
NSLog(#"viewcontroller.m update index");
//add my own parse program
PFQuery *query = [PFQuery queryWithClassName:#"Pictures"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
NSLog(#"picture queried");
NSLog(#"array %#",objects);
NSArray *imageFilesArray = [[NSArray alloc]initWithArray:objects];
PFObject *imageObject = [imageFilesArray objectAtIndex:index];
PFFile *imageFile = [imageObject objectForKey:#"imageFile"];
// scrolling.hidden = NO;
// [scrolling startAnimating];
NSLog(#"pffile %#",imageFile);
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if(!error){
// scrolling.hidden = YES;
//imageView.image = [UIImage imageWithData:data];
pageImages = data;
parseImageData = [UIImage imageWithData:data];
NSLog(#"nsdata translated %#",parseImageData);
// pageContentViewController.imageFile = data;
}
}];
}}];
// Create a new view controller and pass suitable data.
PageContentViewController *pageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"PageContentViewController"];
// pageContentViewController.imageFile = self.pageImages[index];
pageContentViewController.titleText = self.pageTitles[index];
NSLog(#"self.pagetitles[index]");
//pageContentViewController.imageFile = parseImageData;
NSArray *pageImagesArray = [NSKeyedArchiver archivedDataWithRootObject:pageImages];
pageContentViewController.imageFile = pageImagesArray[index];
NSLog(#"pagecontentviewcontroller.imagefile is %#",pageContentViewController.imageFile);
NSLog(#"self.parseImageData %lu",(unsigned long)index);
pageContentViewController.pageIndex = index;
return pageContentViewController;
}
//*****************PAGE CONTENT CONTROLLER PART
#import "PageContentViewController.h"
#import <parse/parse.h>
#interface PageContentViewController ()
#end
#implementation PageContentViewController
#synthesize imageFile,titleText,backgroundImageView; //NSData, NSString, IBOutlet UIImage
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//self.backgroundImageView.image = [UIImage imageWithData:imageFile];
backgroundImageView.image = [UIImage imageWithData:imageFile];
self.titleLabel.text = self.titleText;
NSLog(#"Image supposed be loaded...%#",imageFile);
NSLog(#"title supposed be loaded...%#",titleText);
}

Play audio from Parse via UIButton

I've been working on an app that allows audio to be played from Parse (like a social network), but am having trouble getting the code to not have errors.
My .h file
#import <UIKit/UIKit.h>
#interface TalklineViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *wallScroll;
#end
My .m file
#interface TalklineViewController ()
#property (nonatomic, retain) NSArray *wallAudioArray;
#end
#implementation TalklineViewController
#synthesize wallAudioArray = _wallAudioArray;
#synthesize wallScroll = _wallScroll;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getWallAudio
{
//Prepare the query to get all the images in descending order
//1
PFQuery *query = [PFQuery queryWithClassName:#"AudioObject"];
//2
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//3
if (!error) {
//Everything was correct, put the new objects and load the wall
self.wallAudioArray = nil;
self.wallAudioArray = [[NSArray alloc] initWithArray:objects];
[self loadWallViews];
} else {
//4
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
}
-(void)loadWallViews
{
//Clean the scroll view
for (id viewToRemove in [self.wallScroll subviews]){
if ([viewToRemove isMemberOfClass:[UIView class]])
[viewToRemove removeFromSuperview];
}
//For every wall element, put a view in the scroll
int originY = 10;
for (PFObject *audioObject in self.wallAudioArray){
//1
//Build the view with the image and the comments
UIView *wallAudioView = [[UIView alloc] initWithFrame:CGRectMake(10, originY, self.view.frame.size.width - 20 , 300)];
//2
//Add the image
PFFile *audio = (PFFile *)[audioObject objectForKey:#"audio"];
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
userAudio.frame = CGRectMake(0, 0, wallAudioView.frame.size.width, 200);
[wallAudioView addSubview:userAudio];
//3
//Add the info label (User and creation date)
NSDate *creationDate = audioObject.createdAt;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm dd/MM yyyy"];
//4
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, wallAudioView.frame.size.width,15)];
infoLabel.text = [NSString stringWithFormat:#"Uploaded by: %#, %#", [audioObject objectForKey:#"user"], [df stringFromDate:creationDate]];
infoLabel.font = [UIFont fontWithName:#"Arial-ItalicMT" size:9];
infoLabel.textColor = [UIColor whiteColor];
infoLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:infoLabel];
//5
//Add the comment
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 240, wallAudioView.frame.size.width, 15)];
commentLabel.text = [audioObject objectForKey:#"comment"];
commentLabel.font = [UIFont fontWithName:#"ArialMT" size:13];
commentLabel.textColor = [UIColor whiteColor];
commentLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:commentLabel];
//6
[self.wallScroll addSubview:wallAudioView];
originY = originY + wallAudioView.frame.size.width + 20;
}
//7
//Set the bounds of the scroll
self.wallScroll.contentSize = CGSizeMake(self.wallScroll.frame.size.width, originY);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The problem line is:
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
Any help is greatly appreciated!
UIButton doesn't have an audioWithData method, so that's the biggest issue here; instead, add a target to the button to play the audio with a seperate method:
UIButton *userAudio = [UIButton buttonWithType:UIButtonTypeSystem];
[userAudio setFrame:CGRectMake(20, 20, 100, 44)];
[userAudio setTitle:#"Play Audio!" forState:UIControlStateNormal];
[userAudio addTarget:self action:#selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:userAudio];
- (void)playAudio
{
// Your audio data and playing code here
// audio.getData
}

UITableViewController with UIPageViewController in UIViewController

What I m Thinking to do is ? there is one MainViewController in which there are two UIViews one loaded UITableViewController and other UIPageViewController.
In TableViewController, there are list of pdf's names. But when i click of the pdf list, it does not loads the PageViewController with new pdf in context.
Pdf file names are store in .plist file, Pdfs are fetch from NSBundle or NSDocumentDirectory
In TableViewController
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Play *play = (Play *)[[self.sectionInfoArray objectAtIndex:indexPath.section] play];
Quotation *qute = [play.Details objectAtIndex:indexPath.row];
if ([qute.Key isEqualToString:#"ABC"])
{
AppDelegate *app = [[UIApplication sharedApplication]delegate];
app.strpdfname = qute.Value;
MiddleViewController *mid = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
ContentViewController *cvc = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
[mid viewDidLoad];
[cvc viewDidLoad];
}
else
{
MainViewController *vc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[vc viewDidLoad];
}
}
In PageViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.modelArray = [[NSMutableArray alloc] init];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
NSURL *targetURL = [NSURL fileURLWithPath:path];
originalPDF = CGPDFDocumentCreateWithURL((__bridge CFURLRef)targetURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(originalPDF);
for (int index = 0; index < numberOfPages ; index++)
{
[self.modelArray addObject:[NSString stringWithFormat:#"%d",index]];
}
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageViewController.delegate = self;
self.pageViewController.dataSource = self;
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
contentViewController.labelContents = [self.modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
CGRect pageViewRect = self.view.frame;
pageViewRect = CGRectInset(pageViewRect, 0.0, 0.0);
self.pageViewController.view.frame = pageViewRect;
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == 0)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex - 1];
return contentViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == self.modelArray.count-1)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex + 1];
return contentViewController;
}
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];
self.pageViewController.doubleSided = NO;
return UIPageViewControllerSpineLocationMin;
}
In ContentViewController of PageViewController
-(UIImage*) imageFromPDF:(CGPDFDocumentRef)pdf withPageNumber:(NSUInteger)pageNumber withScale:(CGFloat)scale
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf,pageNumber);
CGRect tmpRect = CGPDFPageGetBoxRect(pdfPage,kCGPDFMediaBox);
CGRect rect = CGRectMake(tmpRect.origin.x,tmpRect.origin.y,tmpRect.size.width*scale,tmpRect.size.height*scale);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context,-50,rect.size.height-30);
CGContextScaleCTM(context,scale,-scale);
CGContextDrawPDFPage(context,pdfPage);
UIImage* pdfImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return pdfImage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
i = [labelContents intValue];
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
if (i!=0)
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path]);
UIImage *img = [[UIImage alloc] init];
img = [self imageFromPDF:pdf withPageNumber:i withScale:1];
UIImageView *imgview1 = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgview1];
}
else
{
UIImage *imgmain = [UIImage imageNamed:#"Diary4.png"];
UIImageView *imgvmain = [[UIImageView alloc] initWithImage:imgmain];
imgvmain.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y,580,self.view.frame.size.height);
[self.view addSubview:imgvmain];
}
}
In MainViewController
-(void)viewDidload
{
leftView = [[UIView alloc] initWithFrame:CGRectMake(5,25, 200,715)];
leftView.backgroundColor = [UIColor clearColor];
tvc = [[TableViewController alloc] initWithStyle:UITableViewStylePlain];
tvc.plays = self.plays;
tvc.view.frame = leftView.frame;
leftView.clipsToBounds = YES;
[leftView addSubview:tvc.view];
[self.view addSubview:leftView];
middleView = [[UIView alloc] initWithFrame:CGRectMake(107, 30, 575, 670)];
mvc = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
[mvc.view setFrame:middleView.frame];
[middleView addSubview:mvc.view];
[self.view addSubview:middleView];
}
As there is no reload data method for UIPageViewController. I was using UIPageViewController in UIViewController instead of that I use UINavigationController in which the UIPageViewController can be reloaded with dynamic data.So on click of UITableViewController, data is sends to UINavigationController-->UIPageViewController. This has solved the above issue.

[NSURL initFileURLWithPath:]: nil string parameter when trying to load a view

When my view is trying to load, the applications crashes and i get this stack:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
This is my code, i don't really know where to look when this crash is occurred:
#import "Itineraire.h"
#import "SBMapView.h"
#import "SBRouteAnnotation.h"
#import "City.h"
#import "UICGRoutes.h"
#import "SBCheckPointViewController.h"
//#import "SBRouteDetailView.h"
#interface Itineraire(Private)
-(void)customInitialization;
#end
#implementation Itineraire(Private)
-(void)customInitialization
{
// do the initialization of class variables here..
mDirections = [UICGDirections sharedDirections];
mDirections.delegate = self;
}
#end
#implementation Itineraire
#synthesize map = mMap;
#synthesize startPoint = mStartPoint;
#synthesize endPoint = mEndPoint;
#synthesize loadBtn = mLoadBtn;
#synthesize annotationArray = mAnnotationArray;
#synthesize travelMode = mTravelMode;
#synthesize destination;
#synthesize routes;
#synthesize mAnnotations;
#synthesize mRouteArray;
#synthesize mRouteDetail;
//Invoked when the class is instantiated in XIB
-(id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if( self)
{
[self customInitialization];
}
return self;
}
// 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 {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
[self customInitialization];
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Google Maps";
self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 49, self.view.frame.size.width, self.view.frame.size.height)];
//self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 381)];
[self.view addSubview:mMap];
self.view.backgroundColor = [UIColor blackColor];
self.annotationArray = [[NSMutableArray alloc]init];
self.routes = [[UICGRoutes alloc]init];
if (mDirections.isInitialized) {
[self updateRoute];
}
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
}
- (void)viewWillDisappear:(BOOL)animated;
{
[super viewWillDisappear:YES];
}
#pragma mark -
#pragma mark Instance Methods
- (void)updateRoute
{ /*
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
options.travelMode = mTravelMode;
City *mFirstCity = [[[City alloc]init] autorelease];
mFirstCity.mCityName = #"Paris";//mStartPoint;
//[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
//added
NSMutableArray * DestinationCityArray = [[NSMutableArray alloc]init];
[DestinationCityArray addObject:#"Berlin"];
[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
*/
//
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init] ;
options.travelMode = mTravelMode;
City *mFirstCity = [[City alloc]init];
mFirstCity.mCityName = #"Amsterdam";//mStartPoint;
NSMutableArray *dest=[[NSMutableArray alloc]init];
[dest addObject:#"Berlin"];
[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:dest options:options];
}
-(void)loadRouteAnnotations
{
self.mRouteArray = [mDirections routeArray];
NSLog(#"mRouteArray %#",mRouteArray);
self.mAnnotations = [[NSMutableArray alloc]init];
for (int idx = 0; idx < [mRouteArray count]; idx++) {
NSArray *_routeWayPoints1 = [[mRouteArray objectAtIndex:idx] wayPoints];
NSArray *mPlacetitles = [[mRouteArray objectAtIndex:idx] mPlaceTitle];
self.annotationArray = [NSMutableArray arrayWithCapacity:[_routeWayPoints1 count]-2];
mLoadBtn.title = #"OFF";
mLoadBtn.target = self;
mLoadBtn.action = #selector(removeRouteAnnotations);
for(int idx = 0; idx < [_routeWayPoints1 count]-1; idx++)
{
mBetweenAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[_routeWayPoints1 objectAtIndex:idx]coordinate]
title:[mPlacetitles objectAtIndex:idx]
annotationType:SBRouteAnnotationTypeWayPoint];
[self.annotationArray addObject:mBetweenAnnotation];
}
[mAnnotations addObject:mAnnotationArray];
[self.map.mapView addAnnotations:[mAnnotations objectAtIndex:idx]];
NSLog(#"map %#",mMap);
}
}
-(void)showCheckpoints
{
SBCheckPointViewController *_Controller = [[SBCheckPointViewController alloc]initWithNibName:#"SBCheckPoints" bundle:nil];
[self.navigationController pushViewController:_Controller animated:YES];
NSMutableArray *arr = [[mDirections checkPoint] mPlaceTitle];
_Controller.mCheckPoints = arr ;
}
//
-(void)removeRouteAnnotations
{
NSMutableArray *mTempAnnotation;// = [mAnnotations retain];
for (int idx = 0; idx < [mTempAnnotation count]; idx++) {
[mMap.mapView removeAnnotations:[mTempAnnotation objectAtIndex:idx] ];
}
mLoadBtn.title = #"ON";
mLoadBtn.target = self;
mLoadBtn.action = #selector(loadRouteAnnotations);
}
#pragma mark <UICGDirectionsDelegate> Methods
- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
[self updateRoute];
}
- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
- (void)directionsDidUpdateDirections:(UICGDirections *)indirections {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UICGPolyline *polyline = [indirections polyline];
NSArray *routePoints = [polyline routePoints];
[mMap loadRoutes:routePoints]; // Loads route by getting the array of all coordinates in the route.
UIToolbar *tools = [[UIToolbar alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
tools.clearsContextBeforeDrawing = NO;
tools.clipsToBounds = NO;
tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
// anyone know how to get it perfect?
tools.barStyle = -1; // clear background
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:2];
// Create a standard Load button.
self.loadBtn = [[UIBarButtonItem alloc]initWithTitle:#"ON"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(loadRouteAnnotations)];
[buttons addObject:mLoadBtn];
// Add Go button.
UIBarButtonItem *mGoBtn = [[UIBarButtonItem alloc] initWithTitle:#"Go"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(showCheckpoints)];
[buttons addObject:mGoBtn];
// Add buttons to toolbar and toolbar to nav bar.
[tools setItems:buttons animated:NO];
UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = twoButtons;
//Add annotations of different colors based on initial and final places.
SBRouteAnnotation *startAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
title:mStartPoint
annotationType:SBRouteAnnotationTypeStart];
SBRouteAnnotation *endAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
title:mEndPoint
annotationType:SBRouteAnnotationTypeEnd];
[mMap.mapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation,nil]];
}
- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
#pragma mark -
#end
I tried to put my code on a new project (empty application) and it worked fine, i didn't understand that error and its possible causes.
EDIT:
I tried to track the problem by elimination,and my code worked fine when i remove this method:
//Invoked when the class is instantiated in XIB
-(id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if( self)
{
[self customInitialization];
}
return self;
}
However, when i run, my app doesn't display me the route between the two points (The purpose of the app). So this method seems important for the whole class because without it, i couldn't get the route and in the other side when it's there, the app crashes. How should i deal with this contradiction?
#Vince is putting you on the right track. Since the problem is in an NSURL method being called by a framework (Google Maps in this case) you need to debug what you are passing to the framework. You have the source for the framework also right? You can set breakpoints in loadWithStartPoint:endPoint:options:] to see what's going on.
One thing I did notice is you are passing an NSMutableArray as the endPoint param when I believe it expects an NSString.

Resources