json photo path format in xcode - json

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

Related

Can't get data on detailviewcontroller with Hpple parsing

I am a beginner in Obj-C and I try to make an app with this raywenderlich tutorial.
I parse html page with Title of articles (mininglife.ru) , also I getting an urls of each articles and keep it in an NSMutableArray for using it in my DetailviewController.
But when I try to pull urls off and put it in NSUrl nothing happens. I've tried a lot of ways, Can you help me with it and try to explain if I do something wrong. Thank you.
-(void)loadArticles{
Articlelist *urlOfArticle = [_objects objectAtIndex:self]; // from previous parsing
NSURL *articleUrl = [NSURL URLWithString:urlOfArticle.url];// I think this string is wrong, or?
NSData *htmlUrlsData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:htmlUrlsData];
NSString *articleNameXpath = #"/html/body/div[1]/div/div[1]/main/article/h1";
// NSString *articleContentXpath = #"//div[#class'entry-content']//p";
NSArray *articleNameNodes = [articleParser searchWithXPathQuery:articleNameXpath];
// NSArray *articleContentNodes = [articleParser searchWithXPathQuery:articleContentXpath];
NSMutableArray *newArticleArray = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNameNodes) {
Article *newArticleName = [[Article alloc] init];
[newArticleArray addObject:newArticleName];
newArticleName.name = [[element firstChild] content];
}
_articleName = newArticleArray;
[self.tableView reloadData];
}
Change interface to this
#interface MasterViewController () {
NSMutableArray *_articles;
}
#end
Add this to MasterViewController
- (void)loadArticles
{
NSURL *articlesUrl = [NSURL URLWithString:#"http://mininglife.ru"];
NSData *articlesHtmlData = [NSData dataWithContentsOfURL:articlesUrl];
TFHpple *articlesParser = [TFHpple hppleWithHTMLData:articlesHtmlData];
NSString *articlesXpathQueryString = #"/html/body/div[1]/div/div[1]/main/article/h1";
NSArray *articlesNodes = [articlesParser searchWithXPathQuery:articlesXpathQueryString];
NSMutableArray *newArticles = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articlesNodes) {
Article *article = [[Article alloc] init];
[newArticles addObject:article];
article.title = [[element firstChild] content];
article.url = [element objectForKey:#"href"];
}
_articles = newArticles;
[self.tableView reloadData];
}
Change DetailviewController.h's interface to
#class Article;
#interface DetailViewController : UIViewController
#property (strong, nonatomic) Article *article;
#property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#end
Change DetailViewController.m to
#import "DetailViewController.h"
#import "Article.h"
#import "TFHpple.h"
#implementation DetailViewController
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadArticle];
}
- (void)loadArticle
{
NSURL *articleUrl = [NSURL URLWithString:self.article.url];
NSData *articleHtmlData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:articleHtmlData];
NSString *articleXpathQueryString = #"//div[#class'entry-content']//p";
NSArray *articleNodes = [articleParser searchWithXPathQuery:articleXpathQueryString];
NSMutableArray *newArticleContents = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNodes) {
[newArticleContents addObject:[[element firstChild] content]];
}
NSLog(#"%#", newArticleContents);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Detail", #"Detail");
}
return self;
}
#end
Don't forget to change all call to loadTutorials to loadArticles in MasterViewController. PS: This example only prints the articles content to the console
Your xPath might be wrong as well

How to put JSON element into UITextView?

I have a MySQL database and a PHP script that work perfectly. However, I was wondering how I could get this data from JSON format to a UITextView. I also have a table being populated with 2 other JSON elements. Thanks!
TableInfo.h
#import <Foundation/Foundation.h>
#interface TableInfo : NSObject
#property (nonatomic, strong) NSString *Title;
#property (nonatomic, strong) NSString *SubTitle;
#property (nonatomic, strong) NSString *Description;
#end
HomeModel.h
#import <Foundation/Foundation.h>
#protocol HomeModelProtocol <NSObject>
- (void)itemsDownloaded:(NSArray *)items;
#end
#interface HomeModel : NSObject <NSURLConnectionDataDelegate>
#property (nonatomic, weak) id<HomeModelProtocol> delegate;
- (void)downloadItems;
#end
HomeModel.m
#import "HomeModel.h"
#import "TableInfo.h"
#interface HomeModel()
{
NSMutableData *_downloadedData;
}
#end
#implementation HomeModel
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://gandouhaiti.ueuo.com/service.php"];
NSLog(#"Donwload the JSON file");
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSLog(#"Create the request");
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
NSLog(#"Create the NSURLConnection");
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Inititalize the data object");
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
TableInfo *newdata = [[TableInfo alloc] init];
newdata.Title = jsonElement[#"Title"];
newdata.SubTitle = jsonElement[#"SubTitle"];
newdata.description = jsonElement[#"Description"];
// Add this question to the locations array
[_locations addObject:newdata];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
#end
If you wan to display the JSON in UITextView in storyboard, kindly try the following:
#implementation ViewController
NSString * JSON;
-(void) viewDidLoad
{
JSON = //get data from remote;
NSString *stringForTextView = #"";
NSData *data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if([array count] >0)
{
for(NSDictionary *d in array)
{
stringForTextView = [NSString stringWithFormat:#"Title:%#\nSubTitle:%#\nDescription:%#\n", [d valueForKey:#"Title"], [d valueForKey:#"SubTitle"], [d valueForKey:#"Description"]];
}
}
_textView.text = stringForTextView;
}
#end

How to parse HTML to search for content specific needles

Given the NSString below which was originally converted from a CData object retrieved from parsing an XML document with NSXMLParser, how can I obtain the following properties of the book: title, book image cover, author , price, and rating?
Here is my rudimentary solution for obtaining the following properties
Book Title - I could probably obtain this by looking at the riRssTitle span class, but then I would have to figure out how to read the title between the ahref url tag to obtain the title
Book Image - I would have to get by grabbing the first URL http://ecx.images-amazon.com/images/I/41Lg22K3ViL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU02_.jpg and then leaving everything up to http://ecx.images-amazon.com/images/I/41Lg22K3ViL omitting the rest, and then appending the .jpg tag to have a complete url for image retrieval at a later point.
Book Author - I'd have to follow the same step as step 1 but instead searching for the riRssContributor span tag.
Book Price - Here there is no price tag thats common across all items, one thing I do see in common though is that the price is always in a font tag where it then sits in a BOLD tag.
Rating - which can probably be retrieved by looking for the URL that contains the word stars and then grab the numbers that follow it, 4 means 4 stars, any number with -5 appended to it means an extra .5 stars. so 3-5 would mean 3.5 stars.
Whats the best way of doing this without it getting messy? Also I dont like how my code can break should Amazon decide to change the way it displays it's URLS, my app relies on amazon maintaining its url naming conventions.
For now though, is this the best way forward? Is there a quick parser that can achieve what I wish to do?
This is an example of an amazon RSS feed: http://www.amazon.co.uk/gp/rss/bestsellers/books/72/ref=zg_bs_72_rsslink
Here is the below CData NSString data I retrieve for each item.
<div style="float:left;">
<a class="url" href="http://www.amazon.co.uk/Gone-Girl-Gillian-Flynn/dp/0753827662/ref=pd_zg_rss_ts_b_72_9">
<img src="http://ecx.images-amazon.com/images/I/41Lg22K3ViL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU02_.jpg" alt="Gone Girl" border="0" hspace="0" vspace="0" />
</a>
</div>
<span class="riRssTitle">
Gone Girl
</span>
<br />
<span class="riRssContributor">
Gillian Flynn
<span class="byLinePipe">(Author)</span>
</span>
<br />
<img src="http://g-ecx.images-amazon.com/images/G/02/x-locale/common/icons/uparrow_green_trans._V192561975_.gif" width="13" align="abstop" alt="Ranking has gone up in the past 24 hours" title="Ranking has gone up in the past 24 hours" height="11" border="0" />
<font color="green">
<strong></strong>
</font> 674 days in the top 100
<br />
<img src="http://g-ecx.images-amazon.com/images/G/02/detail/stars-4-0._V192253865_.gif" width="64" height="12" border="0" style="margin: 0; padding: 0;"/>(5704)
<br />
<br />
Buy new:
<strike>£9.07</strike>
<font color="#990000">
<b>£3.85</b>
</font>
<br />
60 used & new from
<span class="price">£2.21</span>
<br />
<br />(Visit the
Bestsellers in Crime, Thrillers & Mystery list for authoritative information on this product's current rank.)
TFHpple is definitely the library to go with to parse HTML. (>1000 stars on github)
https://github.com/topfunky/hpple
Here's the obj-c solution for that RSS feed:
NSString *stringURL = #"http://www.amazon.co.uk/gp/rss/bestsellers/books/72/ref=zg_bs_72_rsslink";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple * doc = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *titleElements = [doc searchWithXPathQuery:#"//span[#class='riRssTitle']/a"];
for (TFHppleElement *element in titleElements)
{
NSString *title = element.firstChild.content;
NSLog(#"title: %#", title);
}
NSArray *imageElements = [doc searchWithXPathQuery:#"//a[#class='url']/img"];
for (TFHppleElement *element in imageElements)
{
NSString *image = element.attributes[#"src"];
NSMutableArray *parts = [[image componentsSeparatedByString:#"/"] mutableCopy];
NSArray *pathParts = [parts.lastObject componentsSeparatedByString:#"."];
[parts removeLastObject];
[parts addObject:[NSString stringWithFormat:#"%#.%#",pathParts.firstObject, pathParts.lastObject]];
image = [parts componentsJoinedByString:#"/"];
NSLog(#"image: %#", image);
}
NSArray *authorElements = [doc searchWithXPathQuery:#"//span[#class='riRssContributor']/a"];
for (TFHppleElement *element in authorElements)
{
NSString *author = element.firstChild.content;
NSLog(#"author: %#", author);
}
NSArray *priceElements = [doc searchWithXPathQuery:#"//font/b"];
for (TFHppleElement *element in priceElements)
{
NSString *price = element.firstChild.content;
NSLog(#"price: %#", price);
}
NSArray *ratingElements = [doc searchWithXPathQuery:#"//img"];
for (TFHppleElement *element in ratingElements)
{
if (![element.attributes[#"src"] containsString:#"stars"])
continue;
NSArray *parts = [element.attributes[#"src"] componentsSeparatedByString:#"-"];
if (parts.count < 5) continue;
NSString *rating = [NSString stringWithFormat:#"%#.%#", parts[3], [parts[4] substringToIndex:1]];
NSLog(#"rating: %#", rating);
}
Like you said, you are at the mercy of Amazon's naming conventions.
You can use TFHpple and TFHppleElement for parsing the above data as your need.
Here is the reference for doing this.
I saw your post on the iOS developer facebook group and thought I'd give my last minute input.
Because amazon doesn't keep a strict naming convention, you have to search through the feed.
This is what I attempt to do, but then I try and make it look less hackish.
If you notice, you'll find that sometimes the feed returns missing values if you try to scour for specific path names, so I've tried to make up for that case too.
For this to work you simply need to download the NSDictionary category from this URL: https://github.com/nicklockwood/XMLDictionary
.h
#import <Foundation/Foundation.h>
#interface JMAmazonProcessor : NSObject
+(NSArray*)processAmazonResponseWithXMLData:(NSData*)responseObject;
#end
and for
.m
#import "JMAmazonProcessor.h"
#implementation JMAmazonProcessor
+(NSString*)getBookTitleWithArray:(NSArray*)array{
return [[array[0] objectForKey:kAmazonAHREFKey] objectForKey:kAmazonUnderscoreTextKey];
}
+(NSString*)getBookAuthorWithArray:(NSArray*)array{
id bookAuthor = [[array[1] objectForKey:kAmazonAHREFKey] objectForKey:kAmazonUnderscoreTextKey];
if(!bookAuthor){
bookAuthor = [array[1] objectForKey:kAmazonUnderscoreTextKey];
}
if([bookAuthor isKindOfClass:[NSArray class]]){
bookAuthor = [bookAuthor componentsJoinedByString:#" "];
}
return bookAuthor;
}
+(NSString*)getPriceFromDictionary:(NSDictionary*)dictionary{
return [NSString stringWithUTF8String:[[[[dictionary objectForKey:#"font"] lastObject] objectForKey:#"b"] cStringUsingEncoding:NSUTF8StringEncoding]];
}
+(NSString*)getRatingWithCurrentRatingDictionary:(NSDictionary*)ratingDictionary{
NSString * stars;
if([ratingDictionary objectForKey:#"_src"]){
NSString * possibleStarsURL = [ratingDictionary objectForKey:#"_src"];
if([possibleStarsURL rangeOfString:#"stars-" options:NSCaseInsensitiveSearch].location != NSNotFound){
stars = [[[[[possibleStarsURL componentsSeparatedByString:#"stars-"] lastObject] componentsSeparatedByString:#"."] firstObject] stringByReplacingOccurrencesOfString:#"-" withString:#"."];
}
}
return stars;
}
+(NSString*)getRatingFromDictionary:(NSDictionary*)dictionary{
id currentDictionary = [dictionary objectForKey:#"img"];
NSString *rating;
if([currentDictionary isKindOfClass:[NSArray class]]){
for(int i = 0; i < [currentDictionary count]; i++){
NSDictionary *currentRatingDictionary = [currentDictionary objectAtIndex:i];
if((rating = [self getRatingWithCurrentRatingDictionary:currentRatingDictionary])){
break;
}
}
}
else if([currentDictionary isKindOfClass:[NSDictionary class]]){
rating = [self getRatingWithCurrentRatingDictionary:currentDictionary];
}
if(!rating) rating = #"Rating is not currently available";
return rating;
}
+(NSArray*)processAmazonResponseWithXMLData:(NSData*)responseObject{
NSMutableArray *bookEntries = [[NSMutableArray alloc] init];
NSDictionary * itemDictionary = [[NSDictionary dictionaryWithXMLData:responseObject] objectForKey:kAmazonRootNode];
for(int i = 0; i < [[itemDictionary objectForKey:kAmazonFeedItemKey] count]; i++){
RSSBookEntryModel *cBEO = [[RSSBookEntryModel alloc] init];
NSDictionary *currentItem = [[itemDictionary objectForKey:kAmazonFeedItemKey] objectAtIndex:i];
NSString *finalXMLString = [NSString stringWithFormat:#"%#%#%#", kAmazonStartTag, [currentItem objectForKey:kAmazonDescriptionKey], kAmazonEndTag];
NSDictionary *cData = [NSDictionary dictionaryWithXMLString:finalXMLString];
NSArray *bookDetailsDictionary = [cData objectForKey:kAmazonSpanKey];
NSString *bIOURL = [[[[cData objectForKey:#"div"] objectForKey:kAmazonAHREFKey] objectForKey:#"img"] objectForKey:#"_src"];
NSString *bookImageCoverID = [[[[bIOURL componentsSeparatedByString:kAmazonBookCoverBaseURL] lastObject] componentsSeparatedByString:#"."] firstObject];
cBEO.bookTitle = [self getBookTitleWithArray:bookDetailsDictionary];
cBEO.bookAuthor = [self getBookAuthorWithArray:bookDetailsDictionary];
cBEO.bookCoverImageThumbnailURL = [NSString stringWithFormat:#"%#%#%#%#", kAmazonBookCoverBaseURL, bookImageCoverID, kAmazonBookCoverThumbnailSize, kAmazonBookCoverFileExtention];
cBEO.bookCoverImageOriginalURL = [NSString stringWithFormat:#"%#%#%#%#", kAmazonBookCoverBaseURL, bookImageCoverID, kAmazonBookCoverMaxSize, kAmazonBookCoverFileExtention];
cBEO.bookPrice = [self getPriceFromDictionary:cData];
cBEO.bookRating = [self getRatingFromDictionary:cData];
[bookEntries addObject:cBEO];
}
return bookEntries;
}
#end
Sorry.
Here it is:
This is the object model you want to use, its pretty straight forward.
#interface RSSBookEntryModel : NSObject
#property (strong, nonatomic) NSString *bookTitle;
#property (strong, nonatomic) NSString *bookAuthor;
#property (strong, nonatomic) NSString *bookCoverImageThumbnailURL;
#property (strong, nonatomic) NSString *bookCoverImageOriginalURL;
#property (strong, nonatomic) NSData *bookCoverThumbnailImage;
#property (strong, nonatomic) NSData *bookCoverOriginalImage;
#property (strong, nonatomic) NSString *bookPrice;
#property (strong, nonatomic) NSString *bookRating;
-(NSString*)description;
#end
And here are the constants I'm using to keep everything clean.
Constant.h
extern NSString * const kAmazonRootNode;
extern NSString * const kAmazonStartTag;
extern NSString * const kAmazonEndTag;
extern NSString * const kAmazonFeedItemKey;
extern NSString *const kAmazonSpanKey;
extern NSString * const kAmazonDescriptionKey;
extern NSString *const kAmazonUnderscoreTextKey;
extern NSString *const kAmazonAHREFKey;
extern NSString *const kAmazonBookCoverBaseURL;
extern NSString *const kAmazonBookCoverThumbnailSize;
extern NSString *const kAmazonBookCoverMaxSize;
extern NSString *const kAmazonBookCoverFileExtention;
And here's the Constants.m file.
NSString * const kAmazonRootNode = #"channel";
NSString * const kAmazonStartTag = #"<startTag>";
NSString * const kAmazonEndTag = #"</startTag>";
NSString * const kAmazonFeedItemKey = #"item";
NSString *const kAmazonSpanKey = #"span";
NSString * const kAmazonDescriptionKey = #"description";
NSString *const kAmazonUnderscoreTextKey = #"__text";
NSString *const kAmazonAHREFKey = #"a";
NSString *const kAmazonBookCoverBaseURL = #"http://ecx.images-amazon.com/images/";
NSString *const kAmazonBookCoverThumbnailSize = #"._SL100";
NSString *const kAmazonBookCoverMaxSize = #"._SL500";
NSString *const kAmazonBookCoverFileExtention = #".jpg";
This is a pretty weak alternative here, but maybe it helps somehow:
//title
console.log("TITLE: " + $(".riRssTitle").text().trim());
//image
console.log("IMAGE: " + $(document).find("img").attr("src"));
//author
console.log("AUTHOR: " + $(".riRssContributor").find("a").text().trim());
//new price and striked price
var new_price_striked_element = $("a:contains('Buy new')").siblings("strike");
if(new_price_striked_element){
console.log("NEW PRICE STRIKED: " + new_price_striked_element.text().trim());
}else{
console.log("NEW PRICE: " + $("a:contains('Buy new')").siblings("b").text().trim());
}
//used price
console.log("USED PRICE FROM: " + $(".price").text().trim());
//stars
var url = $("img[src*='stars']").attr("src");
var myRegexp = /stars-([0-9]-[0-9])/g;
var match = myRegexp.exec(url);
console.log("STARS: " + match[1]);
EXAMPLE:http://jsfiddle.net/qpuaxtv3/

Unable load a url from a database

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

Show JSON content depending on user id iOS

I want to show the content depending on user id.
The user log-in to the App, after the successful login, he will see the content depending on his id that is retrieved from the JSON file which is connected the the external mysql database.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *jsonURL = [NSURL URLWithString:#"http://api.example.com/page.php?user_id=1"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}
My problem is :
How to make " 1 " in ( user_id=1 ) dynamic, in a way, it will be changed automatically when the user log-in to his account.
Prepare URL dynamically
NSString *userID = #"23";//Get your userID after login
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://api.example.com/page.php?user_id=%#",userID];
you can use StringWithFormat Method of NSString Class, This methods helps you in creating dynamic NSString Objects,
- (void)viewDidLoad
{
[super viewDidLoad];
NSString userId = #"your user id here";
NSURL *jsonURL = [NSURL URLWithString:[NSString StringWithFormat:#"http://api.example.com/page.php?user_id=%#",userId]];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}