I am getting response from web service, the response is based on comma separated URl
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"ResponseData: %#", str);
And its output is like
ResponseData: http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg,http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg
I want to pass the response to my Images Gallery Which takes URL like below format
networkImages = [[NSArray alloc] initWithObjects:#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg",#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg",nil];
How can I format my response to #"URL",#"URL" so that I can store it into some variable e,g;abc and pass that to
networkImages = [[NSArray alloc] initWithObjects:abc,nil];
NSString has a method componentsSeparatedByString: which does exactly this.
networkImages = [str componentsSeparatedByString:#","];
I think you have two ways :
First way; (that i have already using in my news App)
* You must use JSON result.
* If you want you can use SBJsonParser and SDWebImage
NSError *myError = nil;
NSString *link = [NSString stringWithFormat:#"http://www.myexamplenews.com/mobil-app.php?q=imageList&id=%i",galleryId];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse *response=nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&myError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if (myError == nil)
{
NSArray *jsonGalleryDetail = [jsonParser objectWithString:jsonString];
jsonParser = nil;
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: jsonGalleryDetail];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
}
GalleryDetailView.h
#interface GalleryDetailView : UIView
{
}
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *)myList;
#end
GalleryDetailView.m
#implementation GalleryDetailView
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *) myList;
{
self = [super initWithFrame:frame];
if (self)
{
//Your code here
for (NSString *str in myList)
{
NSURL *imageURL = [NSURL URLWithString:str];
//This is SDWebImage extension.
UIImage *image = [UIImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
}
}
return self;
}
#end
Second way ;
NSArray *arr = [ResponseData componentsSeparatedByString:#","];
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: arr];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
I prefer to use JSON data. It is up to you. I hope this information will be helpful for you.
Related
NSURL *url =[NSURL URLWithString:
#"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
Serialisation part is done below
(void)connectionDidFinishLoading{
NSDictionary *allDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *loans = [allDict objectForKey:#"loans"];
countryArray = [[NSMutableArray alloc] init];
for (NSDictionary *diction in loans) {
Country *countryObj = [[Country alloc]init];
NSString *sector = [diction objectForKey:#"sector"];
countryObj.sector = sector;
NSDictionary *imageID = [diction objectForKey:#"image"];
NSString *img = [imageID objectForKey:#"id"];
countryObj.idValue=img;
NSString *activity = [diction objectForKey:#"activity"];
countryObj.activity = activity;
NSString *name = [diction objectForKey:#"name"];
countryObj.name = name;
NSDictionary *con = [diction objectForKey:#"location"];
NSString *world = [con objectForKey:#"country"];
countryObj.country= world;
NSString *towname = [con objectForKey:#"town"];
countryObj.down=towname;
[countryArray addObject:countryObj];
}
}
This contains both images and data. I need to store the image into cache.
Please use SDWebImage it contains everything you need. I am using this library for 2 years already.
Follow that tutorial which contains how to cache images inside a UIImageView with a simple one line of code and also a class that prefetches all the images in background, just create an NSArray with all the images you want to prefetch.
Hope that helps!
I have program which use an API to collect the schedule list of different TV channels, I have maybe 10 TV channels so I don't want to add manually the 10 items in my tabBar controller
I use this code to collect my channels :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *url = [NSString stringWithFormat: #"https://apis.is/tv"];
// Download JSON
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
// Parse JSON
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:JSONData //1
options:kNilOptions
error:&error];
NSArray* jsonResult = [json objectForKey:#"channels"];
_channelList = [[NSMutableArray alloc] init];
for (id item in jsonResult) {
TVShow *TVChannel = [[TVShow alloc] init];
TVChannel.channel = [item objectForKey:#"name"];
TVChannel.endpoint = [item objectForKey:#"endpoint"];
[_channelList addObject:TVChannel];
}
}
I wanted to know how with that I can add a tap bar item for each channel
Thanks guys
This code is working fine for me... You can just copy and paste it... :)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *url = [NSString stringWithFormat: #"https://apis.is/tv"];
// Download JSON
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
// Parse JSON
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:JSONData //1
options:NSJSONReadingAllowFragments
error:&error];
NSArray* jsonResult = json[#"results"][0][#"channels"];
_channelList = [[NSMutableArray alloc] init];
for (id item in jsonResult) {
TVShow *TVChannel = [[TVShow alloc] init];
TVChannel.channel = item[#"name"];
TVChannel.endpoint = item[#"endpoint"];
[_channelList addObject:TVChannel];
}
NSMutableArray *tabViewControllers = [[NSMutableArray alloc] init];
NSInteger tabTag = 0;
for (TVShow *show in self.channelList) {
ViewController1 *view1 = [[ViewController1 alloc] initWithNibName:#"ViewController1" bundle:[NSBundle mainBundle]];
[tabViewControllers addObject:view1];
view1.mainLabel.text = show.channel;
view1.tabBarItem = [[UITabBarItem alloc] initWithTitle:show.channel
image:nil
tag:tabTag];
tabTag++;
}
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:tabViewControllers];
[self.window setRootViewController: tabBarController];
[self.window makeKeyAndVisible];
return YES;
}
I am trying to set up a UITableView in my application that will display several different RSS feeds. Basically, one table for a News, Calendar, and Audio podcast. The issue is that not all of the feeds have the same tags. Some use <link> while others use <guid>. How can I go about setting up the code to handle different kinds of RSS? I have an NSObject called RSSEntry that takes strings from each of the tags to reuse later in setting up the table, but I get a nil argument if I try to get a <link> tag from one of the ones that uses <guid>.
-(void)viewDidLoad {
[super viewDidLoad];
[self refresh];
}
- (void)refresh {
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"http://ipreacher.wordpress.com/feed",#"http://www.316apps.com/Fritch/Sermons.xml",
nil];
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleContent = [item valueForChild:#"content:encoded"];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleContent:articleContent] autorelease];
[entries addObject:entry];
}
}
}
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
To convert the data, I am using:
- (NSDictionary *)downloadPlist:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (!err) {
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];
if (!errorDescription)
return samplePlist;
[errorDescription release];
}
return nil;
}
Can anyone please tell me how to do that?
or this:
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];
Try this code:
NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", #"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"Login" ofType:#"plist"];
[dictionary writeToFile:path atomically:YES];
//here Login is the plist name.
Happy coding
I have the following api method which returns NSData. I have called this method in another view controller. How to convert the NSData to NSInteger?
-(NSData *)getBusXMLAtStop:(NSString*)stopnumber
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString: [NSString stringWithFormat:#"http://www.google.com/ig/api?weather=,,,50500000,30500000",stopnumber]]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",dataReply);
return dataReply;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
api *ap = [[api alloc]init];
NSData *str = [ap getBusXMLAtStop:#"1"];
// Here is where I want to convert str into NSInteger type. How is this possible?
NSLog(#"this is success %#",ap.dataReply);
TWeatherParser *parser = [[TWeatherParser alloc]init];
[parser getInitialiseWithData:ap.dataReply];
[parser release];
[ap release];
}
Well, if you know that your data is really representing a single integer, the simplest way is the following:
NSData *data = ...;
int i;
[data getBytes: &i length: sizeof(i)];
UPD: NSInteger is defined depending on the architecture of the target processor and is either int or long. Feel free to replace int by NSInteger in the code above.
I'm also not sure that your data is an actual number and not it's string representation. In this case use something like
NSString *str = [[[NSString alloc] initWithData:data encoding:(encoding you need)] autorelease];
NSInteger value = [str intValue];
You can find a convenience initialiser on NSString called initWithData:. Please check out the documentation for more info.
EXAMPLE:
NSString * s = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];