This code allows me to pull image names from my mysql lite database without any issues.
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage * image = [UIImage imageNamed: self.munsterData.image];
self.imageView.image = image;
}
I would also like to pull specific urls from my database and load them into a UIWebView using this code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL * myUrl = [[NSURL alloc] initWithString: self.munsterData.twitter];
NSURLRequest * myNSURLRequest = [[NSURLRequest alloc]initWithURL:myUrl];
[twitterView loadRequest:myNSURLRequest];
}
What am I doing wrong? My app instantly crashes when I select the url link. If I replace:
NSURL * myUrl = [[NSURL alloc] initWithString: self.munsterData.twitter];
with
NSURL * myUrl = [[NSURL alloc] initWithString: #"http://www.google.com"];
The google website loads successfully. But for some reason I cannot get url's from my database to load.
munsterData:
#property (nonatomic, retain) NSMutableArray * munsterData;
twitter:
const char * twitterStr = sqlite3_column_text(statement, 7);
NSString * twitter = [NSString stringWithUTF8String:twitterStr];
p.twitter = twitter;
Put this right after the [super viewDidLoad]; and provide feedback.
NSLog(#"%#", self.munsterData.twitter);
if ([self.munsterData.twitter isKindOfClass:[NSString class]]) {
NSLog(#"is string");
}
You Code is perfect for loading any url in UIWebview. good way to start. But make sure the below points before loading url in UIWebview with the example of your code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL * myUrl = [[NSURL alloc] initWithString: self.munsterData.twitter];
NSURLRequest * myNSURLRequest = [[NSURLRequest alloc]initWithURL:myUrl];
[twitterView loadRequest:myNSURLRequest];
}
Debug your code and check if "self.munsterData.twitter" is getting url or not. Good way to program is to check if your string has value or not only than after than perform another operation on string.
Check if you string Contains "http://" or "https://" in your "self.munsterData.twitter". if not available than please add using string with format method of NSString Class.
For Better Programming, Please use the method for converting in to real url with the below method:
- NSString *url_String = [self.munsterData.twitter strgingByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Related
i have a jpg file in my database,
how can i used json/php build in my Xcode project?
my jpg link in php format like this:
[{"photo_path":"photo_path.jpg,"title":"test topic""]}
i know when i build "title" part,i can use NSString format,
but in "photo_path.jpg" part,did i use NSString also??
#property (nonatomic, strong) NSString * title;
#property (nonatomic, strong) NSString * photo_path;
#property (strong, nonatomic) IBOutlet UITextView *detaillabel;
#property (strong, nonatomic) IBOutlet UIImageView *photolabel;
and here is my json.m part:
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
HomeArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
NSString * titletopic = [[json objectAtIndex:i] objectForKey:#"title"];
NSString * detailinfo = [[json objectAtIndex:i] objectForKey:#"detail"];
NSString * photo = [[json objectAtIndex:i] objectForKey:#"photo_path"];
NSString * dateinfo = [[json objectAtIndex:i] objectForKey:#"date"];
HomeDetail * home2 = [[HomeDetail alloc]initWithTitle:titletopic
andDetail:detailinfo
andPhoto_path:photo
andDate:dateinfo];
[HomeArray addObject:home2];
}
[self.myTableView reloadData];
}
You need to store the path/url of your image in your database. By path I mean local path (if the image is stored locally) or URL if it's somewhere on the interwebz.
Fetch that URL whichever way pleases you (JSON is fine), and make your way through the JSON to retrieve the NSString of that URL.
( you appear to have that all done already, in your NSString *photo
Though i suggest you rename "photo" with photoPath or something more clear because the photo name strongly suggests it's already an image, which it isn't yet :)
Then simply apply this where you need the UIImage object:
NSURL *url = [NSURL URLWithString:photo];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO];
You can then add it to an imageview using setImage: or .image
I'm building an app for my Drupal based website. I currently have my iOS application pulling data from the MySQL database (e.g. Article titles and descriptions). Does anyone know what sort of code I would use to display an article's corresponding image (uploaded via a Drupal field) in an UIImageView?
Here's a quick snippet of the code I'm using to pull text from my Drupal site.
DoctorsViewController.h
#interface DoctorsViewController : UIViewController {
IBOutlet UITableView *DoctorsTableView;
NSArray *Doctors;
NSMutableData *data;
}
DoctorsViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"MY URL HERE"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
Doctors = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
[DoctorsTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete - please make sure that you're connected to 3G or Wi-Fi." delegate:nil
cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView: (UITableView *)tableview
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Doctors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *DoctorsTableIdentifier = #"DoctorsCell";
DoctorsCell *cell = (DoctorsCell *)[tableView dequeueReusableCellWithIdentifier:DoctorsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DoctorsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.firstnameLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"node_title"];
cell.descriptionLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"Opening Paragraph"];
return cell;
}
That isn't as straightforward as it sounds - Drupal stores its field data in a very specific way, and URIs to the images are addressed with a schema rather than having a relative or absolute path (e.g. public://path/to/image.jpg as opposed to /sites/default/files/path/to/image.jpg)
You can get the image URIs for a node straight from the DB like this (assuming your article type uses the standard field_image field):
SELECT fm.uri
FROM {file_managed} fm
INNER JOIN field_data_field_image fi ON fi.entity_type = 'node' AND fi.bundle = 'article' AND fi.deleted = 0 AND fi.field_image_fid = fm.fid
WHERE fi.entity_id = <nid>
Where <nid> is the node ID. From there you'll need to perform whatever logic you need to translate the paths to something useful for your iOS app. Drupal uses file_create_url() to perform the same task, so that's your best starting point for inspiration. Depending on your setup you may well get away with just doing a string replace on public:// to http://example.com/sites/default/files/.
Long term, you might want to look at adding the Services module and consuming the REST API in your app, instead of querying the DB directly. It'll take a lot of the strain of preparing Drupal's data out of your hands so you can just deal with what you need.
Im having issues with this code reading some .json files, it works fine on json that can be read via IE like a webpage but wont work on files that the url is tring to download them like a ftp style.
In the end im looking at populating labels with the json info once this works but cant see what around the URLRequest is causing it.
This is what code im testing it with:
// WDViewController.h
#import <UIKit/UIKit.h>
#interface WDViewController : UIViewController{
NSArray *jsonArray;
NSMutableData *data;
}
#property (weak, nonatomic) IBOutlet UILabel *outputLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender;
#end
// WDViewController.m
#import "WDViewController.h"
#interface WDViewController ()
#end
#implementation WDViewController
#synthesize outputLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender{
NSURL *url = [NSURL URLWithString:#"http://gooruism.com/feed/json"];
NSURLRequest *data = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
// Loop through jsonArray
for (int i = 0; i< jsonArray.count; i++)
{
outputLabel.text = [[jsonArray objectAtIndex:i] objectForKey:#"889"]; // Set Labels
}
}
#end
The json file and url are just one that I found looking for a solution via Google and are only for testing.
After a lot more Google and learning some more about json,
Ive got the code working.
Ended up being more of a null exemption from empty indexes and not calling objectForKeys correctly, as was leaving strings that errored when then using to populate a label.
Code I finally got to work:
//
// WDViewController.m
// JSON Test
#import "WDViewController.h"
#interface WDViewController ()
#end
#implementation WDViewController
#synthesize testLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender
{
// Set network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Set json url.
NSURL *url = [NSURL URLWithString:#"<url for json>"];
// get the url page into the nsdata object.
NSData *jsonData = [NSData dataWithContentsOfURL:url];
// Read json (from jasondata) and convert to object.
if ( jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
NSLog (#"%#", result);
NSLog(#"Test 1");
// Retrieve array and show in log
NSLog(#"From status index: %#", [result objectForKey:#"status"]);
// Retrieve data and log
NSLog(#"From profile.handle index: %#", [[result objectForKey:#"profile"]objectForKey:#"handle"]);
NSLog(#"Next Test 2"); // Populate label with data handle
yestLabel.text = [[result objectForKey:#"profile"]objectForKey:#"handle"];
NSLog(#"End of Tests");
}
}
#end
in part of my app (storyboard) I have a table view with various rows, and when I select a row, an html file should be displayed. Instead when I select a row, I get a blank screen instead.
I thought I needed another view controller after the tableview controller, but I get the same issue whether I have one or not.
In my table controller .m file I have the following code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
articleIndex = indexPath.row;
WebView *selectedArticle = [[WebView alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:selectedArticle animated:YES];
[selectedArticle release];
That is allowing me to select a row and the screen changes to a blank one, rather than loading the relevant html file.
I have in my resources folder a .h and .m file as follows:
webView.h
#import <UIKit/UIKit.h>
#import "globals.h"
#interface WebView : UIViewController{
NSArray *articleNames;
IBOutlet UIWebView *webView;
}
#property(nonatomic, retain)IBOutlet UIWebView *webView;
#end
webView.m
#import "WebView.h"
#implementation WebView
#synthesize webView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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];
articleNames = [[NSArray arrayWithObjects:
#"chapter1",
#"chapter2",
#"chapter3",
#"chapter4",
#"chapter5",
#"chapter6",
nil] retain];
NSString *chapterName = [[NSString alloc] initWithString:[articleNames objectAtIndex:articleIndex]];
NSString *path = [[NSBundle mainBundle] pathForResource:chapterName ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[chapterName release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I can't see what I have done wrong here, any advice? I'm not sure how to get the html files to display or where I need to make changes to allow it. If I remove the HTML files from the project the app crashes so it's definitely loading them but for some reason not displaying...
Well first off where is "articleIndex" I see you set it in your tableViewController but it is not webView.h or webView.m. I would suggest first adding in a NSLog
NSURL *url = [NSURL fileURLWithPath:path];
NSLog(#"Article URL:%#", url);
This will let you see if the url is correct first. Second it looks like you connected your UIWebView with interface builder, so make sure that the webView is connect correctly. You can also test the webView buy using:
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: #"http://www.apple.com"]];
And see if apple.com loads. If it does then you know your issue is with your html files or the paths to them.
I'm trying to display a local html file from a three20 table controller. The table shows up correctly, but when I select the item, all I get is a blank screen. If I use an external URL, the page shows correctly. I haven't tried using UIWebView, but I was wondering if there was an easy way using the Three20 framework.
Thanks.
EDIT: I forgot that has changed recently...
Assuming you have registered a TTWebController in your navigator that way :
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"*" toViewController:[TTWebController class]];
You can simply open a local html file that way :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTOpenURL([url description]);
Then all you have to to is to add TTTableLinkedItem or subclass (almost all of TT*Cell are) to your dataSource with a local file URL like that :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTTableTextItem *item = [TTTableTextItem itemWithText:#"foobar" URL:[url description]];
Much simpler that what I wrote before...
ENDOFEDIT
Forget whats under, unless you're interested in others solutions... (more complex... or not, see last one)
Basically here is how you load content in a UIWebView :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
The three20 TTWebController can take a request in a query :
- (id)initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query {
if (self = [self initWithNibName:nil bundle:nil]) {
NSURLRequest* request = [query objectForKey:#"request"];
if (nil != request) {
[self openRequest:request];
} else {
[self openURL:URL];
}
}
return self;
}
So to open a local html file in a TTWebController you could do this :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[[TTNavigator navigator] openURLAction:
[[[TTURLAction actionWithURLPath:#"url://to/your/ttwebcontroller"]
applyQuery:[NSDictionary dictionaryWithObject:ulrRequest
forKey:#"request"]]
applyAnimated:YES]];
Now the last part, to trigger this from a TTTableViewController...
You have in your ViewController to implement :
- (void)didSelectObject:(id)object atIndexPath:(NSIndexPath*)indexPath {
// there you retrieve a *TTTableItem* corresponding to your row
// and call previous snippet from URL...
// TTTableItem class has userInfo property you could use:
TTTableItem *item = (TTTableItem *)object;
NSString *htmlFile = item.userInfo.
[self openLocalHtmlFile:htmlFile];
}
Hope that helps!
Nothing tested, at all, should not compile or whatsoever, but that is a solution.
That's a solution using basic three20 + iOS features. You could also write a TTCustomWebController inheriting from TTWebController that would take urls like #"myapp://openLocalHtml?file=credits" that's not that hard to do...
...That here is a draft :
#interface TTCustomWebController : TTWebController {}
#end
#implementation TTCustomWebController
- (id)initWithFile:(NSString *)name {
self = [super init];
if (self) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:#"html"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
[self openURL:URL];
}
return self;
}
#end
Then you could simply use TTTableLinkedItem in your datasource pointing to these #"myapp://openLocalHtml?file=credits"...
Good luck! :)