Google Chart URL can not be loaded by WebView (NSUrl remains nil) - ios4

I try to load an URL from Google Chart in a UIWebView. Here is the interesting code:
NSString *urlAddress = #"http://chart.apis.google.com/chart?chxr=0,5,398.333&chxs=0,676767,11.167,0.833,l,676767&chxt=x&chs=300x225&cht=lc&chco=3D79FF&chd=s:ilowy0zvvzrligikqsrl&chg=14.3,-1,0,0&chls=2&chm=B,C5D4EABB,0,0,0|R,FF0000,0,0,0.03|R,000000,0,0.3,0.33";
NSURL *url = [NSURL URLWithString:urlAddress];
if (url == nil) {
NSLog(#"URL error occured");
} else {
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}
The message "URL error occured" is logged.
Thanks in advance!

NSString *str =#"http://chart.apis.google.com/chart?chf=bg,s,00000000&chs=300x225&cht=p3&chco=E91616|0000FF&chd=t:50,21&chp=2.9&chma=0,0,0,7";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *chartURL = [NSURL URLWithString:str];
Use like this.

I've found the solution on my own:
The NSUrl object does not accept pipes (|) within an URL. One has to escape the pipes by replacing them with %7c

Related

Can I use Reader mode (as in Safari) in UIWebView?

I want convert webpage from my app as safari reader mode. Is it real?
you mean this?
#import <SafariServices/SafariServices.h>
NSString *sURL = #"http://google.com";
NSURL *URL = [NSURL URLWithString:sURL];
SFSafariViewController *safari = [[SFSafariViewController alloc] initWithURL:URL]; // 1.
//SFSafariViewController *safari = [[SFSafariViewController alloc] initWithURL:URL entersReaderIfAvailable:YES]; // 2.
[self presentViewController:safari animated:YES completion:nil];

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!

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];

CoreData "Error validating url for store"

I'm having a problem in my application, CoreData works as it should in he simulator - but not on the device.
I receive an
2010-09-30 12:45:07.500 CoreDataTutorial_iOS[130:307] Unresolved error Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x1412a0 {NSUnderlyingException=Error validating url for store}, {
NSUnderlyingException = "Error validating url for store";
I'm calling for the PersistentStoreCoordinator in this function (which throws the error above):
-(NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
if(persistentStoreCoordinator_ != nil)
return persistentStoreCoordinator_;
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:#"corebase.sqlite"]];
NSError *anError = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:aStoreURL options:nil error:&anError])
{
NSLog(#"Unresolved error %#, %#", anError, [anError userInfo]);
abort();
}
return persistentStoreCoordinator;
}
I'm setting a break point, on "objc_exception_throw", to see what the aStoreURL is, and it is:
file://localhost/var/mobile/Applications/BE9A2982-BDC3-405D-A201-FB78E9E0790B/Documentscorebase.sqlite
I notice it's not itself adding the final "/" after "/Documents".
When I created the URL this way
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:#"/corebase.sqlite"]];
It seems to have worked, or at least got passed that part.
Shouldn't this function be appending that part itself?
-(NSString*) applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}
It works fine in the simulator, what is the right practice?
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingFormat: #"corebase.sqlite"]];
should be
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"corebase.sqlite"]];
stringByAppending*PathComponent* instead of stringByAppending*Format*.
This nice little bug was brought to you by autocomplete :-)
Why it worked in the simulator? I guess because you are allowed to create files everywhere on the harddisk. So the Simulator created Documentscorebase.sqlite in your Apps Directory. You should check if it's there.
On the iphone you are limited to the Documents directory and are not allowed to create files everywhere.

Resources