Loading Text from a .rtf - text

Hei guys,
I'm trying to load a long text from a .rtf file and I want to show this text in a UITextView.
I store all the .rtf files in a folder called "rtf" into the "Supporting Files" folder.
This is my code.
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem)
{
self.textView.text = [self setTextForTextView:[self.detailItem description]];
}
}
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *path = [NSString stringWithFormat:#"rtf/%#.rtf" ,description];
NSLog(#"%#" ,path);
NSString *myText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return myText;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Text";
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
But It doesn't show me the text and I don't understand why...
Thanks!

I just solved in this way:
-(NSString *)setTextForTextView:(NSString *)description
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:description ofType:#"txt"];
if (filePath)
{
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (myText)
{
return myText;
}
}
}
I hope this will help some people in the future! :D

Related

iOS8 & xcode6 no longer plays sound

I'm having a problem that appeared after the big update to iOS 8 and XCode6.
When I try to play sound with AudioToolBox nothing comes out the speakers. I am using the simulator.
I have two variants of the function that plays the sound.
-(void)playSound:(NSString *)fileName
{
SystemSoundID soundEffet = [self soundEffect];
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:fileName withExtension:#"mp3"];
NSString *URLString = [soundURL absoluteString];
if ([[NSFileManager defaultManager] fileExistsAtPath:URLString])
{
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &soundEffet);
AudioServicesPlaySystemSound(soundEffet);
} else {
NSLog(#"error, file not found: %#", fileName);
}
}
This fails the file exists at path check.
-(void)playSound:(NSString *)fileName
{
SystemSoundID soundEffet = [self soundEffect];
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
if ([[NSFileManager defaultManager] fileExistsAtPath:URLString])
{
NSURL *pathURL = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &soundEffet);
AudioServicesPlaySystemSound(soundEffet);
} else {
NSLog(#"error, file not found: %#", fileName);
}
}
This one just doesn't play anything.
I am very sure that the file name that I am using is correct.
Does anyone have any ideas about what changed so that these no longer work? And most important: how do I fix this?
So I figured it out! (Cue the flailing kermit arms.) Reinhard Manner's comment is what pointed me in the right direction.
I did indeed end up using AVAudioPlayer. Here's what I ended up with.
-(void)playSound:(NSString *)fileName
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
soundPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
if (soundPlayer != nil)
{
[soundPlayer play];
} else {
NSLog(#"could not play with file %#", fileName);
}
}
Not included here is the soundPlayer synthesized at the top of the file and made a a property in the .h file.
I still don't know why AudioToolbox stopped working. But this is what works, and I'm going with it.
Also, Reinhard Manner, you may want to post that type of thing as an answer next time, so that you can get more credit!

CoreDataTableViewController does not reload on return from segue

I have several CoreDataTableViewControllers that utilize the helper class from Paul Hegarty's course. Everyone of them works except this one, and I cannot see a difference.
When the table first comes up, it is correctly populated and the segue executes properly when a cell is selected. However when I hit the back button, the table displays (null), (null) everywhere.
I have tried every variant of calling [self useDocument] that I can think of, still to no avail. Any thoughts? Thanks in advance.
//
// TeamTableViewController.m
//
#import "TeamTableViewController.h"
#import "iTrackAppDelegate.h"
#import "CoreDataTableViewController.h"
#import "SchoolRecords.h"
#import "ScheduleViewController.h"
#interface TeamTableViewController ()
#property NSInteger toggle;
#end
#implementation TeamTableViewController
#synthesize iTrackContext = _iTrackContext;
#synthesize schoolSelected = _schoolSelected;
-(void) setSchoolSelected:(SchoolRecords *)schoolSelected
{
_schoolSelected = schoolSelected;
}
-(void) setITrackContext:(NSManagedObjectContext *)iTrackContext
{
if(_iTrackContext != iTrackContext){
if (!iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
_iTrackContext = cdh.context;
} else {
_iTrackContext = iTrackContext;
}
}
[self useDocument];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)setupFetchedResultsController // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"SchoolRecords"];
// no predicate because we want ALL the Athletes
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:#"schoolName" ascending:YES],
nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.iTrackContext
sectionNameKeyPath:nil
cacheName:nil];
__block NSInteger myCount;
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.iTrackContext performBlock:^(void){NSError* requestError = nil;
myCount = [self.iTrackContext countForFetchRequest:request error:&requestError];
NSLog(#"In %# and count of iTrackContext = %lu", NSStringFromClass([self class]),(unsigned long)myCount);
}];
if (!myCount || myCount == 0) {
[self displayAlertBoxWithTitle:#"No Teams" message:#"Have you added athletes yet? \nPlease go to Add Athletes" cancelButton:#"Okay"];
}
});
}
- (void)useDocument
{
if (self.iTrackContext) {
[self setupFetchedResultsController];
} else {
NSString* errorText = #"A problem arose opening the search results database of Athletes.";
[self displayAlertBoxWithTitle:#"File Error" message:errorText cancelButton:#"Okay"];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (!self.iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
[self setITrackContext:cdh.context];
} else {
NSLog(#"In %# of %#. Getting ready to call useDocument",NSStringFromSelector(_cmd), self.class);
[self useDocument];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// If divide into sections use line below otherwise return 1.
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Do not really need this with only one section, but makes code usable if add sections later.
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"teamInformation";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SchoolRecords *schoolResults = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString* titleText = schoolResults.schoolName;
cell.textLabel.text = titleText;
cell.detailTextLabel.text = [NSMutableString stringWithFormat:#"%#, %#", schoolResults.schoolCity, schoolResults.schoolState];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
# pragma navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
[self setSchoolSelected:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// be somewhat generic here (slightly advanced usage)
// we'll segue to ANY view controller that has a photographer #property
if ([segue.identifier isEqualToString:#"scheduleDetailSegue"]) {
// use performSelector:withObject: to send without compiler checking
// (which is acceptable here because we used introspection to be sure this is okay)
NSLog(#"Preparing to passing school with schoolID = %#", self.schoolSelected.schoolID);
[segue.destinationViewController convenienceMethodForSettingSchool:self.schoolSelected];
}
}
- (void) displayAlertBoxWithTitle:(NSString*)title message:(NSString*) myMessage cancelButton:(NSString*) cancelText
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:myMessage
delegate:nil
cancelButtonTitle:cancelText
otherButtonTitles:nil];
[alert show];
}
#end
Well, I am not certain what the problem was. I ended up deleting the "offending" TableViewControllers in StoryBoard and recreated them. That did the trick. In retrospect, I wonder if I did not specify the wrong type of segue from my tabViewController. But I deleted it before I thought of that possibility.

uiwebview not loading any content

I am not able to load any webpages.
Any idea why this could be?
The frame for the webview (printed from the debugger)
<UIWebView: 0x8a49840; frame = (0 0; 320 241); autoresize = TM+BM; layer = <CALayer: 0x8a498f0>>
Here is my code:
#import "ViewController.h"
#interface ViewController () <UIWebViewDelegate>
#end
#implementation ViewController
#synthesize webview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.webview.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated
{
}
- (IBAction)buttonPress:(id)sender {
NSLog(#"pressed");
NSURL *theUrl = [NSURL URLWithString:#"www.google.com"];
NSError *e ;
// just for test - ALSO returning nil!!!
NSString *str = [NSString stringWithContentsOfURL:theUrl encoding:NSUTF8StringEncoding error:&e];
NSLog(#"%#",str);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
[self.webview loadRequest:theRequest];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"page is loading");
}
// this method is never called
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"finished loading");
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
#end
use this one it'l work.
problem: in your url http:// was missed
NSURL *theUrl = [NSURL URLWithString:#"http://www.google.com"];
You don't have proper URL.
Because +URLWithString: expects a protocol (e.g. http://, https://),
if you have www.google.com in that case it cannot build a URL.So please try to use like this..
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
You may also check if your link doesn't contain the "http://" or "https://" and add it.
NSString *website = #"www.google.com";
NSRange textRangeHTTP = [[website lowercaseString] rangeOfString:#"http://"];
NSRange textRangeHTTPS = [[website lowercaseString] rangeOfString:#"https://"];
if((textRangeHTTP.location == NSNotFound) && (textRangeHTTPS.location == NSNotFound))
website = [NSString stringWithFormat:#"http://%#",website];
NSURL *theUrl = [NSURL URLWithString:website];
just use this in your buttoned pressed method
NSURL *theUrl = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
[self.webview loadRequest:theRequest];
always make sure that using the protocol type that is "http://" is prefixed to the web url string
(Xcode 5 iOS 7) Needed to update an Universal App for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

Saving contents of NSMutableArray containing custom class objects

I have a custom class "Bookmark" which contains an NSString. I use a NSMutableArray to store instances of this class thus making a bookmark list which I display in a UITableView with a UITableViewCell prototype.
Would someone please give some advice/example on how to save the instances within the NSMutableArray to a file (and perhaps an example how to load them). I can't get any examples I've searched to work. I've tried converting the array to NSData and using NSKeyedArchiver without success. I've also tried converting to an NSArray but can't get it to work.
Within the custom class I've implemented encodeWithCode and initWithCoder.
I need to save before the app closes and I want to load the list when the app is started.
I'm stuck... :(
EDIT: At the request of Ageektrapped, here are the code snippets:
Inside the implementation of my Bookmark class:
- (void) encodeWithCoder: (NSCoder *) encoder
{
[encoder encodeObject:self.address forKey:#"Address"];
}
- (id) initWithCoder: (NSCoder *) decoder
{
self = [super init];
if (self != nil)
{
self.address = [decoder decodeObjectForKey: #"Address"];
}
return self;
}
In my MasterViewController
self.bookmarks is a NSMutableArray containing bookmark objects. (When the code below is called, there is at least one entry in the bookmarks array.)
NSString *docFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];
NSString *filename = [docFolder stringByAppendingPathComponent:#"data.plist"];
NSLog(#"File : %#", filename);
NSLog(#"Bookmarks : %d", self.bookmarks.count);
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: self.bookmarks ];
if ([data writeToFile: filename atomically: YES])
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
I finally figured out what my problem was.
Because I'm debugging on my iPhone device, some folders are not writable. The code I was using was asking for a location in such an area (NSDocumentationDirectory):
After finally finding =>
How can I get a writable path on the iPhone? I understood my problem and got it working.
What I needed to do was replace:
NSString *docFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];
NSString *filename = [docFolder stringByAppendingPathComponent:#"data.plist"];
with:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *libFolder = [paths objectAtIndex: 0];
NSString *filename = [libFolder stringByAppendingPathComponent: #"data.archive"];
I also changed these lines (to be consistent with the example) from:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: self.bookmarks ];
if ([data writeToFile: filename atomically: YES])
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
to:
BOOL success = [NSKeyedArchiver archiveRootObject: self.bookmarks toFile: filename];
if (success)
{
NSLog(#"Successful write");
} else {
NSLog(#"Failed write");
}
.
The code to read the file into the NSMutableArray on application startup is:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *libFolder = [paths objectAtIndex: 0];
NSString *filename = [libFolder stringByAppendingPathComponent: #"data.archive"];
self.bookmarks = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];

Mail composer didn't display under my UIWebView

I have a MainController and detailedcontroller. When I popover the Book selection and select a Book, the detailcontroller display an UIWebView with the book articles :
#interface IpadBooksViewController : UITableViewController {
SearchResult *searchResult;
IpadArticleViewController *detailController;
IpadMainViewController *mainController;
UIPopoverController *popover;
}
Into the UIWebView, I display an Email icon and catch the scheme :
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *url = [request URL];
NSString *scheme = [url scheme];
NSString *host = [url host];
if ([[url description] hasSuffix:#"next"]) {
NSLog(#"next Show");
}
BOOL isShareLinks = [host isEqualToString:#"displayShareLinks"];
BOOL isFavoriteLinks = [host isEqualToString:#"displayFavoriteLinks"];
if ([#"myappurl" isEqualToString:scheme] && (isShareLinks || isFavoriteLinks)) {
self.selectedArticleNumber = [url.path lastPathComponent];
if (isShareLinks) {
[self sendMailArticleNumber:selectedArticleNumber];
} else if (isFavoriteLinks) {
NSLog(#"ipad favorite clicked");
[self toggleFavorite:selectedArticleNumber];
Broker *broker = [[Broker alloc] init];
[broker loadProjects:self];
[broker release];
}
}
return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}
Action is supposed to display the MFMailController under my UIWebView, but nothing is displayed without error message :
- (void) sendMailArticleNumber:(NSString *)articleNumber {
MFMailComposeViewController* composer = [[MFMailComposeViewController alloc] init];
composer.mailComposeDelegate = self;
[composer setSubject:#"Article"];
NSString *messageBody = [Article fetchBody:articleNumber bookId:bookId];
[composer setMessageBody:messageBody isHTML:YES];
[self presentModalViewController:composer animated:YES];
[composer release];
}
Any help will be welcomed. I did try creating a popover, addView atIndex without success ... Let me know if you need more code.
David
I did solve the issue by loading the controller into the delegate as following :
[((PublilexAppDelegate*)[[UIApplication sharedApplication] delegate]) sendMailArticleNumber:selectedArticleNumber bookId:self.bookId];
And then into the Delegate :
- (void) sendMailArticleNumber:(NSString *)articleNumber bookId:(NSString*)bookId {
MFMailComposeViewController* composer = [[MFMailComposeViewController alloc] init];
composer.mailComposeDelegate = self;
[composer setSubject:#"Article"];
NSString *messageBody = [Article fetchBody:articleNumber bookId:bookId];
[composer setMessageBody:messageBody isHTML:YES];
[self->navigationController presentModalViewController:composer animated:YES];
[composer release];
}
And to dismiss and comeback to the previous view :
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self->navigationController dismissModalViewControllerAnimated:YES];
// [self dismissViewControllerAnimated:YES completion:nil];
// [((PublilexAppDelegate*)[[UIApplication sharedApplication] delegate]) navigateToIpadMain];
}

Resources