How to add "advertisements" in the UIScrollView like BBC News app? - ios

I have created the news app which use the "UIScrollView + UIWebView" to let users to swipe through different news. However, I would like to ask whether it's possible for me to add the advertisements like the BBC News app or not, which users will see the advertisements while scrolling horizontally.
I was trying to use addSubView while scrolling (scrollViewDidScroll) but it replaces the existing content.
I realize BBC News app do the things like this,
Users swipe through the news --> After swiping a few times --> show the ads (in position 5, for instance) --> users swipe from start to the end again --> the ads appear again, but this time could be in position 3).
But I just don't know how to make it work for my app. Any clue? thanks in advance.

You probably already have a functionality, where You have stored news articles data in some array. Or You fetch data from database into some array.
Well - I think the easiest way would be just to add advert_data in this news array.
For example - You fetch from db in array:
NSArray *mArray = #[
"news1",
"news2",
"news3",
"news4",
"news5",
"news6"];
then You could simply - iterate it all through, and add advert data. For example
int counter = 0;
while (counter < [mArray count])
{
int mTmp = 3+(arc4random() % 2); // atleast 3, but up to 5?
counter +=mTmp;
[mArray insertObject:"advert" atIndex:counter];
counter +=1; //we added one object, so we need to adjust counter
}
Then simply - when You try to load corresponding data in webview, check if content is not "advert". If it is - load some random advert html from somewhere.
P.S. I guess, Your data arrays will have NSManagedObjects, instead of strings. Then You can check if [mArray objectAtIndex:i] (when You try to load it into webview)- is NSManagedObject or a string value.
I hope You understand this idea.

Related

Change Table View Cell Color If message is New

I am new in iOS so please help me. I am getting some messages from server with a key "messageId". I am showing those messages in tableview. Now I have to differentiate that if there is new message which is being open first time in that tableview, I have to change the colour of that message in the cell.
cell.notificationMessageDate.text = [[self.notifications objectAtIndex:indexPath.row] valueForKey:#"msgCreatedDate"];
cell.notificationMessageText.text = [self stringByStrippingHTML:[[self.notifications objectAtIndex:indexPath.row] valueForKey:#"message"]];
NSString *str = [[self.notifications objectAtIndex:indexPath.row] valueForKey:#"messageId"];
self.isAlreadyExist = false;
if (str ) {
cell.backgroundColor = [UIColor whiteColor];
} else {
}
#AADi i see that you are getting message from notifications. I dont know what structure you have implemented.
To implement what you want, what i feel is you must implement a dictionary or array where you store your data from wherever you are fetching it. Then pass the count of the array or dict. to table. Now maintain a variable which stores the previous count of the array or dict. In cell for row, compare the index path with the previous count of the array or dict. If the index path is greater then previous count simply change the background for the cell at that index path and update the value of previous count with current count.
If you don't understand or have any doubts then ask here.
Hope it will help you.
A word of advice, its not a good approach to check if message is new locally. If a user uninstalls the app and reinstall it then all the messages would appear new to the user even thought she may have read them.
A better approach is to send boolean variable, something like seen or read, along with other details of message from the server and display the cells accordingly. To mark a message as read or seen you can make an API call to the server with the messageID reflecting it in the backend.

Indexed tableView with Array of Unknown Contents?

I want to create an index for my tableView songsTable with the quick-jump index on the right. songsTable displays the contents of songsArray, which shows a list of songs from the user's iPod library:
However, all tutorials that show how to index a tableView already know their contents. These are the tutorials I've seen so far: AppCoda, iPhoneDevCentral, Innofied, among a few others. They all use NSDictionaries to store their contents, I'm using an NSArray.
I tied to follow the AppCode tutorial and I got stuck at the first hurdle:
-(void)createAlphabetArray
{
self.alphabetArray = [[NSMutableArray alloc]initWithCapacity:26];
for (int i=0; i< songs.count; i++)
{
NSString *firstletter=[[songs objectAtIndex:i]substringToIndex:1];
if (![self.alphabetArray containsObject:firstletter]) {
[self.alphabetArray addObject:firstletter];
}
}
[songs sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)]; //sorting array in ascending array
NSLog(#"%#", self.alphabetArray);
}
I'm really, really confused and I can't find any other tutorials that are useful for this situation. Any help would be much appreciated. Thanks.
EDIT: I say 'unknown contents' because I don't know what the contents of songsArray is, like the other tutorials, which actually provide the content of the tables.
You can't add objects to NSArray one by one. You can either add them all in one line, or copy an array to your array.
What you're probably looking for is NSMutableArray instead of NSArray.
This allows you to add objects at will.
You was probably supposed to implement the logic inside loop slightly different:
NSString *firstLetter = [songsArray[i] substringToIndex:1];
if (![self.alphabetArray containsObject:firstLetter]) {
[self.alphabetArray addObject:firstLetter];
}
UPDATE
This would help you to fix the crash. But I don't still understand what do you mean under unknown content. I don't see anything related to this problem in the provided code.

SPPlaylist items as SPTracks not loading (consistently)

I've been struggling with this for a while now and was looking around for some advice from anyone who's worked with CocoaLibSpotify on iOS (iOS 7 to be exact).
I'm trying to load all the (SPTrack) items in a SPPlaylist. I've looked though the example code and the documentation so I know the best way to observe things is with KVO, however I can't see how that's the best way here.
Looking at the "Guess the Into" example and other sources on GitHub and the web in general, the precess I'm doing is as follows:
Get the SPPlaylist (this is either directly from a the users playlists or created from a saved URL),
Load the playlist with SPAsyncLoading,
Loop though the SPPlaylistItems returned in the SPPlaylist and get all the SPTrack objects,
Pass the array of SPTrack objects into another SPAsyncLoading call,
Display all items from the loadedItems array.
Step 5 is where things seem to go wrong. Sometimes it is fine and I get all the tracks in the playlist displaying. However most of the time it doesn't load them, or only load a few (normally very little).
I've noticed that restarting the phone can sometimes make it work. Though after running the app (or changing the playlist) a couple of time, it stops working again.
When I log each step I get something like the following:
-[ViewController sessionDidLoginSuccessfully:]
Load playlist with URL: spotify:user:XXXXX:playlist:XXXXXXXXXXXXXXXXXXXXXX
Created playlist: <SPPlaylist: 0x16775bc0>: (null) (0 items)
Loaded playlist: <SPPlaylist: 0x16775bc0>: Playlist Name (59 items)
Created SPTrack items: 59
Loaded SPTrack items: 1
Failed to load SPTrack items: 58
As you can see, the user is logged on, with a valid session. Each step works according to plan until the end. Sometimes even if it does load a track, it won't allow me to play it anyway as well returning SP_TRACK_AVAILABILITY_UNAVAILABLE.
I've also added a code snippet below if it helps. But any help would be grateful at this point with this.
Thanks.
- (void)loadPlaylist
{
__weak NSURL *spotifyURL = <URL from saved SPPlaylist>;
NSLog(#"Load playlist with URL: %#", spotifyURL);
[SPPlaylist playlistWithPlaylistURL:spotifyURL inSession:[SPSession sharedSession] callback:^(SPPlaylist *playlist) {
_spotifyPlaylist = playlist;
NSLog(#"Created playlist: %#", _spotifyPlaylist);
[SPAsyncLoading waitUntilLoaded: _spotifyPlaylist timeout:kSpotifyTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
NSLog(#"Loaded playlist: %#", _spotifyPlaylist);
if ([loadedItems count] > 0)
[self loadSpotifyPlaylist];
}];
}];
}
- (void)loadSpotifyPlaylist
{
NSArray *tracksArray = [self tracksFromPlaylistItems:[_spotifyPlaylist items]];
NSLog(#"Created SPTrack items: %d", [tracksArray count]);
if (tracksArray && [tracksArray count] > 0)
{
[SPAsyncLoading waitUntilLoaded:tracksArray timeout:kSpotifyTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
_playlist = loadedItems;
NSLog(#"Loaded SPTrack items: %d", [loadedItems count]);
NSLog(#"Failed to load SPTrack items: %d", [notLoadedItems count]);
[self finishReloadData];
}];
}
_spotifyPlaylist and _playlist are both strong instances and tracksFromPlaylistItems: is the same method used in the "Guess the Info" sample code.
Edit: The kSpotifyTimeout timeout is set to 10.0.
What's your value of kSpotifyTimeout? I think what you're seeing is simply the fact that metadata can take a long time to load (especially yesterday when the Spotify backend seemed to be having trouble, which can happen from time to time).
Generally, loading the entire contents of a playlist at once is bad practice, and you'll see that Guess the Intro doesn't actually care whether all the tracks loaded or not - it just grabs what happened to load and uses those tracks for the game.
A good approach to take is to paginate loading of playlist tracks to match your UI. That is, to only load the tracks your user can see, plus maybe a "screen" or two's worth up and down. As the user scrolls, you can start loading tracks - UIScrollViewDelegates -scrollViewWillEndDragging:withVelocity:targetContentOffset: is particularly good for this, as it lets you see where the user will "land" and start to load tracks for that point. There's some example code for doing this as well as a helper class called SPSparseArray for partially loading content like playlists on the dev branch of CococaLibSpotify (although be aware that dev branch = beta quality).

Implement my own a custom GKTurnBasedMatchmakerViewController

I'm sure there are questions similar to this, but I couldn't find an example. I'm trying to recreate the apple GKTurnBasedMatchmakerViewController for my turn based game with my own custom interface for my turn based iphone game. I'm having trouble getting all the options to display correctly so I was hoping someone had a working example. My current code is this:
-(void)getCurrentGamesFromServer {
[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error) {
if(matches){
for (GKTurnBasedMatch *myMatch in matches) {
//this is, I believe, also where we need to consider invitations. available instance methods provided by GC are: acceptInviteWithCompletionHandler and declineInviteWithCompletionHandler
if(myMatch.status == 1){ //ongoing game
if([myMatch.currentParticipant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]){ //if it's my turn
//here we need to populate the table by adding our matches to mcurrentgamesarray. after all the matches have been added, reload the tableview
NSLog(#"active game that is my turn");
[self.mCurrentGamesArray addObject:myMatch];
}
else{
NSLog(#"other turn or an invite from another player waiting to hear from you");
}
}
}
}
[_mCurrentGamesTableView reloadData];
}];
}
As you can see, the only games I'm grabbing right now are games where the status is 1 (ongoing game) and the current participant ID is my ID.
to get games that were not my turn, I tried doing games where it was not my ID, but it included invites with it and I couldn't figure out how to separate them out.
Basically, I'd like to have a section of games where it is my turn, a section where it is not my turn but games are still active, a section of completed old games, and a section for invites. does anyone have a working example, or a page they can send me to that explains the best practices for what I'm trying to do? Thanks for your help.

MGTwitterEngine + OAuth Load Users Tweets

I am using MGTwitterEngine + OAuth in my project. I would like to load all tweets from the currently logged in user into a NSMutableArray, however I am having difficulty doing so.
Upon successful login I call the following method:
[_engine getUserTimelineFor:_engine.username sinceID:0 startingAtPage:0 count:20];
And then in the delegate method I have the following:
- (void) statusesReceived:(NSArray *)statuses
forRequest:(NSString *) connectionIdentifier
{
for ( NSDictionary *dict in statuses )
{
NSLog(#"%#", [dict objectForKey:#"id" ]);
// tweets is a NSMutableArray previously allocated and initialised
[tweets addObject:[dict objectForKey:#"id" ]];
}
[_engine getUserTimelineFor:_engine.username sinceID:0 startingAtPage:0 count:20];
}
As you can see I am attempting to batch load the current users tweets, 20 at a time.
I believe the issue lies in the fact, I am not incrementing the page parameter. My issue is, I don't understand what a page actually represents, or how to get the total number of pages for any given user.
How can I load all of a users tweets in a simple, and efficient manner?
If you are using tableView to display tweet to user, you can use "Facebook's way". You can show first 20 tweets in the table view and when iPhone user scrolls down and and try to view last tweet (if you are rendering last row of your table view) then send request to get next 20 tweets and so on. So that you don't need to show page numbers and older tweets will get loaded when user wants to view them.
I hope this helps you.

Resources