Utilizing AFNetworking with YouTube UITableView - ios

I'm hoping someone can help. I am able to list YouTube videos in a tableView without AFNetworking. The code looks something like this:
NSURL *url = [[NSURL alloc] initWithString:#"http://gdata.youtube.com/feeds/api/playlists/PLgw1uRYia2CRrFJW7WT4sKoQxvl_pD0c1?v=2&alt=json&max-results=50&key=AIzaSyA8cyh2w-oa5Z5Wzq6em-ir8YCVF8j1zw4&orderby=published"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSString *jsonString = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingAllowFragments error:nil];
NSDictionary *feed = [[NSDictionary alloc] initWithDictionary:[jsonDict valueForKey:#"feed"]];
videoArray = [NSMutableArray arrayWithArray:[feed valueForKey:#"entry"]];
[self.videolist reloadData];
The images have to load so scrolling is really weird. Therefore, I would like to utilize AFNetworking. Here's the code I have tried:
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *feed = [[NSDictionary alloc] initWithDictionary:[responseObject valueForKey:#"feed"]];
videoArray = [NSMutableArray arrayWithArray:[feed valueForKey:#"entry"]];
NSLog(#"radio==%#",videoArray);
[self.videolist reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And over cellForRowAtIndexPath, it looks something like this:
NSDictionary *video = videoArray[indexPath.row];
NSString *title = [video valueForKeyPath:#"title.$t"];
cell.videotitle.text = title;
That doesn't work for some reason, even when there are no errors. Help?

The videolist wasn't linked to the table in the Storyboard. The issue is now resolved.

Related

Objective C setting labels after api call

UPDATE
I am making an api call getPacks() and successfully getting the values of two variables _numberOfPacks and _numberOfAutoRefills.
However, when I try to put it in a label it fails and gives output as (null) Packs & (null) Autorefiils
the calls are made in the following order:
getpacks()-------first (it sets value on _numberOfPacks and _numberOfAutoRefills as global variables
drawQuantity()-----set _numberOfPacks and _numberOfAutoRefills on labels.
-(void) getPacks: (IHPlacedOrder*)order{
NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];
networkQueue.maxConcurrentOperationCount = 5;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://XXXXXXX.XXXXX/%#",order.ID]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if([string isEqualToString:#""]){
} else {
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSLog(#"%#",dict);
_numberOfPacks = [[dict objectForKey:#"prescription_interval"] valueForKey:#"quantity_per_interval"];
_numberOfAutoRefills = [[dict objectForKey:#"prescription_interval"]valueForKey:#"num_intervals"];
NSLog(#"PACKS:%# , AUTOREFILLS:%#",_numberOfPacks,_numberOfAutoRefills);
_quantity.text = [NSString stringWithFormat: #"%#,%#",_numberOfPacks,_numberOfAutoRefills];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%s: AFHTTPRequestOperation error: %#", __FUNCTION__, error);
}];
[networkQueue addOperation:operation];
}
followed by:
-(void)drawQuantity: (IHPlacedOrder*)order{
PPLinearLayoutLabelItem *quantityLabel = [[PPLinearLayoutLabelItem alloc] initWithText:[NSString stringWithFormat:#"%# QUANTITY & %# REFILLS", _numberOfPacks,_numberOfAutoRefills] font:[PPFonts regular18] maxWidth:[LayoutValues getMaxWidthClipped]];
[quantityLabel setPaddingBottom:5];
[quantityLabel setPaddingTop:20];
[self.topContainerContent addObject:quantityLabel];
NSString* quantityText = [NSString stringWithFormat:#"Packs + Autorefills"];
PPLinearLayoutLabelItem *quantity = [[PPLinearLayoutLabelItem alloc] initWithText:quantityText font:[PPFonts genericParagraphFontBold] maxWidth:[LayoutValues getMaxWidthClipped]];
[quantity setPaddingBottom:20];
[self.topContainerContent addObject:quantity];
LinearLayoutHorizontalLine *line1 = [[LinearLayoutHorizontalLine alloc] initWithMaxWidth:[LayoutValues getMaxWidthClipped]];
[self.topContainerContent addObject:line1];
}
I found the solution. I was using wrong method call to set labels. The thing is my application uses PPLinearLayoutLabelItem as a custom built label. I had to call [self.quantity setLabel:#"%#",data_fromapi] to make it work. setText would just set the text within PPLinearLayoutLabelItem class and not set the Label.

load images into cache and display into UIImageView

how can i display image into UICollectionView using Cache and display large image into another
View on UICollectionView didSelect. Here both large and thumb image on CollectionView so next view large image not blank.using EMAsyncImageView
NSURL *url = [NSURL URLWithString:#"http://leewayinfotech.com/mobile/girlwallpaper/api.php?category=abstract&device=i5&hits=all"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"Response String=%#",responseString);
NSError *jsonError;
NSData *trimmedData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:trimmedData options:NSJSONReadingAllowFragments error:&jsonError];
if (jsonError) {
NSLog(#"JSON parse error: %#", jsonError);
return;
}
obj_Array=[[NSMutableArray alloc] init];
obj_Array=[json objectForKey:#"wallpaper"];
//NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.thumb_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.device_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.imgNo_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
for (int i=0; i<[obj_Array count]; i++) {
ImgClass *obj_Class=[[ImgClass alloc] init];
obj_Class.main_id=[[[obj_Array objectAtIndex:i] valueForKey:#"id"] integerValue];
[obj_Class.thumb_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image_thumb"]];
[obj_Class.device_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image2"]];
NSLog(#"Thumb-->%#\n\nDevice-->%#",[obj_Class.thumb_img_Array description],[obj_Class.device_img_Array description]);
[appDelg.my_Array addObject:obj_Class];
}
you use the EGOImageView for image caching support.
You can use SDWebImage.Using SDWebImage you can set image using imageURLString like below with CacheType.
[yourImgView setImageWithURL:[NSURL URLWithString:imageURLString]
placeholderImage:[UIImage imageNamed:#"noimage.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (!error && image)
{
}
}];
Hope it will helps you..

Objective C, update table view after async operation

I am running an async operation which loops through a json data file which should then update a table view.
Here's the code i'm using.
-(void) TopDealsRecieve:(NSString *)Devicetoken;
{
currentcount = 0;
allcontent = newArray;
//Send device token and retireve TopDeals
NSString *mainURL = #"http://myurl.com/api/";
NSString *firstprefix = #"type=apicall&device=";
NSString *deviceIDforURL = [NSString stringWithFormat:#"%#", Devicetoken];
NSString *stringToGoToEncoder = [NSString stringWithFormat: #"%#%#", firstprefix, deviceIDforURL];
NSData *plainData = [stringToGoToEncoder dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSString *returnURL = [NSString stringWithFormat:#"%#%#", mainURL, base64String];
NSURL *returncompletedURL = [[NSURL alloc] initWithString:returnURL];
//Retrieve Dictionary of Top Deals
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:returncompletedURL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Get all output and store for segue
NSLog(#"%#", responseObject);
currentcount++;
numrows = [responseObject valueForKey:#"rows"];
numrowscompare = [numrows integerValue];
allLogos = [[responseObject valueForKey:#"data"] valueForKey:#"logo"];
allcontent = [[responseObject valueForKey:#"data"] valueForKey:#"content"];
allpostode = [[responseObject valueForKey:#"data"] valueForKey:#"postcode"];
NSLog(#"%lu", (unsigned long)allcontent.count);
allname = [[responseObject valueForKey:#"data"] valueForKey:#"name"];
alladdress = [[responseObject valueForKey:#"data"] valueForKey:#"address"];
alladdress2 = [[responseObject valueForKey:#"data"] valueForKey:#"address2"];
alllat = [[responseObject valueForKey:#"data"] valueForKey:#"lat"];
alllong = [[responseObject valueForKey:#"data"] valueForKey:#"lng"];
allstart = [[responseObject valueForKey:#"data"] valueForKey:#"start"];
allfinish = [[responseObject valueForKey:#"data"] valueForKey:#"finish"];
allstartnice = [[responseObject valueForKey:#"data"] valueForKey:#"nicestart"];
allfinishnice = [[responseObject valueForKey:#"data"] valueForKey:#"nicefinish"];
// hide the ticker
[self.tableview reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Top Deals check internet connection!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}
When running the operation all the data comes in fine to the console, however the table view does not update with the correct data. It updates with the data in the all content array from before calling the function.
It seems that the data from the server isn't being passed to the table view quick enough. I somehow need to get the table view to reloadData AFTER the operation has been completed in some sort of queue.
[self.tableview reloadData];
Sorry if not too clear, any help appreciated.
If allContent is the NSArray your UITableViewDatasource uses, then you never update it in your completionBlockWithSuccess, so this isn't a problem of async update but rather a simple mistake : update allContent just before calling reloadData.
(One additionnal remark : using 'Global' arrays is bad!)

how to send array as a parameter in Afnetwoking post method?

hi i need to send a array as a one of the parameter in Afnetworking Query String
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.008.0.28/aaa/a/"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: #"20", #"Miles", [NSArray arrayWithObjects:#"1",#"2",#"3",nil], #"Interval", nil];
[httpClient postPath:iUpdateNotificationMethod parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
But server side we got "Miles":20,"Intervals":null how to fix it
Thanks,
Try This
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:OAuthBaseURL];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:0];
for (int i =0; i < [userIDs count]; i++) {
NSString *userID = [[userIDs objectAtIndex:i] objectForKey:#"id"];
NSDictionary *tmpDict = [NSDictionary dictionaryWithObjectsAndKeys:userID , [NSString stringWithFormat:#"ids[%i]",i], nil];
[parameters addEntriesFromDictionary:tmpDict];
}
[client postPath:#"/user"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *data = (NSData *)responseObject;
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"jsonStr %#",jsonStr);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self showError];
}
];
Since you're submitting an array, AFNetworking is generating a different parameter name and overloads it with the values you supply. For example, your request generates the following querystring:
Interval[]=1&Interval[]=2&Interval[]=3&Miles=20
This is defined in AFHTTPClient.m in the AFQueryStringPairsFromKeyAndValue function.
If you want to keep the original parameter, you should decide how to convert your NSArray to NSString by yourself. For example, you can do something like [myArray componentsJoinedByString:#","] and then split it back to elements on the server. If you choose this method, beware of using characters that might appear in your actual data.
I believe this will work:
params = #{ #"Miles": #"20", #"Interval": #[#"1",#"2",#"3"] };

Access the Dictionary From Json URL

I am Using URL For Access JSON file
I get this From Following code
NSData* data=[jsonString dataUsingEncoding: [NSString defaultCStringEncoding] ];
NSError *error; //where jsonString is string of URL
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonDictionary==nil) {
NSLog(#"Error::Loading");
}else
{
NSArray *array = [jsonDictionary objectForKey:#"categories"];
for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_id"] forKey:#"cat_id"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_name"] forKey:#"cat_name"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_image"] forKey:#"cat_image"];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"cat_list"] forKey:#"cat_list"];
[newsArray addObject:dic];
[categoryArry addObject:[dic valueForKey:#"cat_name"]];
[categoryId addObject:[dic valueForKey:#"cat_id"]];
[categoryImage addObject:[dic valueForKey:#"cat_image"]];
[categoryList addObject:[dic valueForKey:#"cat_list"]];
[dic release];
}
}
and get json Structure Like This
{
"categories": [
{
"cat_id": "15",
"cat_name": "Shop",
"cat_image": null,
"cat_list": [
{
"sub_cat_name": "New Arrivals",
"Cat_Data": [
{
"prod_name": "Generals Coat Biege",
"prod_price": "215.0000",
"prod_image": "honey_beau_lookbook_winter13_febmarch-24.jpg"
}
]
}
]
}
]
}
categoryArry contain only ine value "Shop"
but i want to access "sub_cat_name" in categoryArry and skip the Shop Level....
In short I want to store "sub_cat_name" in to categoryArry.
Surely you just need to do:
NSArray *catlist = [dic valueForKey:#"cat_list"]
NSDictionary *firstcat = [catlist objectAtIndex:0];
NSString *subcatname = [firstcat valueForKey:#"sub_cat_name"];
This assumes of course that you have at least one item in the cat_list array.
I'm using 3rd party library called AFNetworking to make JSON requests and parse the response.
Here's an example:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:#"http://yoursite.com"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"blah/path"
parameters:#{#"jsonKey":#"jsonValue"}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *res, id json) {
// Use the json here
json[#"categories"][0][#"cat_list"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json) {
//Handle Errors
}];
[operation start];
At your code replace:
[categoryArry addObject:[dic valueForKey:#"cat_name"]];
by
[categoryArry addObject:[[dic valueForKey:#"cat_list"][0]] valueForKey:#"sub_cat_name"];
Anyway you could use the jsonDictionary directly instead of creating another dict.

Resources