I've been working on an app that allows audio to be played from Parse (like a social network), but am having trouble getting the code to not have errors.
My .h file
#import <UIKit/UIKit.h>
#interface TalklineViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *wallScroll;
#end
My .m file
#interface TalklineViewController ()
#property (nonatomic, retain) NSArray *wallAudioArray;
#end
#implementation TalklineViewController
#synthesize wallAudioArray = _wallAudioArray;
#synthesize wallScroll = _wallScroll;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getWallAudio
{
//Prepare the query to get all the images in descending order
//1
PFQuery *query = [PFQuery queryWithClassName:#"AudioObject"];
//2
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//3
if (!error) {
//Everything was correct, put the new objects and load the wall
self.wallAudioArray = nil;
self.wallAudioArray = [[NSArray alloc] initWithArray:objects];
[self loadWallViews];
} else {
//4
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
}
-(void)loadWallViews
{
//Clean the scroll view
for (id viewToRemove in [self.wallScroll subviews]){
if ([viewToRemove isMemberOfClass:[UIView class]])
[viewToRemove removeFromSuperview];
}
//For every wall element, put a view in the scroll
int originY = 10;
for (PFObject *audioObject in self.wallAudioArray){
//1
//Build the view with the image and the comments
UIView *wallAudioView = [[UIView alloc] initWithFrame:CGRectMake(10, originY, self.view.frame.size.width - 20 , 300)];
//2
//Add the image
PFFile *audio = (PFFile *)[audioObject objectForKey:#"audio"];
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
userAudio.frame = CGRectMake(0, 0, wallAudioView.frame.size.width, 200);
[wallAudioView addSubview:userAudio];
//3
//Add the info label (User and creation date)
NSDate *creationDate = audioObject.createdAt;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm dd/MM yyyy"];
//4
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, wallAudioView.frame.size.width,15)];
infoLabel.text = [NSString stringWithFormat:#"Uploaded by: %#, %#", [audioObject objectForKey:#"user"], [df stringFromDate:creationDate]];
infoLabel.font = [UIFont fontWithName:#"Arial-ItalicMT" size:9];
infoLabel.textColor = [UIColor whiteColor];
infoLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:infoLabel];
//5
//Add the comment
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 240, wallAudioView.frame.size.width, 15)];
commentLabel.text = [audioObject objectForKey:#"comment"];
commentLabel.font = [UIFont fontWithName:#"ArialMT" size:13];
commentLabel.textColor = [UIColor whiteColor];
commentLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:commentLabel];
//6
[self.wallScroll addSubview:wallAudioView];
originY = originY + wallAudioView.frame.size.width + 20;
}
//7
//Set the bounds of the scroll
self.wallScroll.contentSize = CGSizeMake(self.wallScroll.frame.size.width, originY);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The problem line is:
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
Any help is greatly appreciated!
UIButton doesn't have an audioWithData method, so that's the biggest issue here; instead, add a target to the button to play the audio with a seperate method:
UIButton *userAudio = [UIButton buttonWithType:UIButtonTypeSystem];
[userAudio setFrame:CGRectMake(20, 20, 100, 44)];
[userAudio setTitle:#"Play Audio!" forState:UIControlStateNormal];
[userAudio addTarget:self action:#selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:userAudio];
- (void)playAudio
{
// Your audio data and playing code here
// audio.getData
}
Related
I made this autocomplete code for searching places. And search correctly but bounds and region not set. show places out of my bounds.
#import "SearchViewController.h"
#import <GooglePlaces/GooglePlaces.h>
#import <GoogleMaps/GoogleMaps.h>
#import GooglePlaces;
#interface SearchViewController () <GMSAutocompleteViewControllerDelegate,GMSAutocompleteFetcherDelegate>
#end
#implementation SearchViewController{
UITextField *_textField;
UITextView *_resultText;
GMSAutocompleteFetcher* _fetcher;
GMSPlacesClient *_placesClient;
GMSCoordinateBounds *_bounds;
GMSAutocompleteFilter *_filter;
}
- (void)viewDidLoad {
[super viewDidLoad];
//APIkEy
[GMSPlacesClient provideAPIKey:#"AIzaSyBYA7KlOZ3VqjQTG4x0R1jaCt9I1-1EVBc"];
_placesClient = [GMSPlacesClient sharedClient];
self.view.backgroundColor = [UIColor whiteColor];
self.edgesForExtendedLayout = UIRectEdgeNone;
// Set bounds
CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(35.818074, 51.586990);
CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(35.557071, 51.098099);
_bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:neBoundsCorner coordinate:swBoundsCorner];
// Set up the autocomplete filter.
_filter = [[GMSAutocompleteFilter alloc] init];
_filter.type = kGMSPlacesAutocompleteTypeFilterNoFilter;
// Create the fetcher.
_fetcher = [[GMSAutocompleteFetcher alloc] initWithBounds:_bounds filter:_filter];
_fetcher.delegate = self;
// Set up the UITextField and UITextView.
_textField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 0, self.view.bounds.size.width - 5.0f, 44.0f)];
_textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[_textField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
_resultText =[[UITextView alloc] initWithFrame:CGRectMake(0, 45.0f, self.view.bounds.size.width, self.view.bounds.size.height - 1.0f)];
_resultText.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
_resultText.text = #"No Results";
_resultText.editable = NO;
[self.view addSubview:_textField];
[self.view addSubview:_resultText];
}
- (void)textFieldDidChange:(UITextField *)textField {
NSLog(#"%#", textField.text);
[_fetcher sourceTextHasChanged:textField.text];
}
#pragma mark - GMSAutocompleteFetcherDelegate
- (void)didAutocompleteWithPredictions:(NSArray *)predictions {
NSMutableString *resultsStr = [NSMutableString string];
for (GMSAutocompletePrediction *prediction in predictions) {
[resultsStr appendFormat:#"%#\n", [prediction.attributedPrimaryText string]];
NSLog(#"sec is: %#",[prediction.attributedSecondaryText string]);
NSLog(#"placeID is: %#", prediction.placeID );
[_placesClient lookUpPlaceID:prediction.placeID callback:^(GMSPlace *place, NSError *error) {
if (error != nil) {
NSLog(#"Place Details error %#", [error localizedDescription]);
return;
}
if (place != nil) {
NSLog(#"Place name %#", place.name);
NSLog(#"Place address %#", place.formattedAddress);
NSLog(#"Place placeID %#", place.placeID);
NSLog(#"Place attributions %#", place.attributions);
NSLog(#"Place latitude %f", place.coordinate.latitude);
NSLog(#"Place longitude %f", place.coordinate.longitude);
} else {
NSLog(#"No place details for %#", prediction.placeID);
}
}];
}
_resultText.text = resultsStr;
}
Setting the bounds only biases results to that rectangle, it isn't a strict restrict.
Hi everyone iam new in objective c, now i try to create the app like "What's the word". I find this tutorial and lerned it as well as i can. But i have some problems. I want when i click on buttons the currentTitle replace the lable in placesView. Button click method in LettersView.m named as "displayChar". I have success in getting currentTitle but now i don't know how to pass it to GameController and paste text on "places".
I will be grateful for any help!
Here is my code
LettersView.h
#import <UIKit/UIKit.h>
#class LettersView;
#protocol LetterClickDelegateProtocol <NSObject>
-(void)letterView:(LettersView*)letterView addChar:(NSString *)addChar;
#end
#interface LettersView : UIImageView
#property (strong, nonatomic, readonly) NSString* letter;
#property (assign, nonatomic) BOOL isMatched;
#property (strong, nonatomic) NSString *clickLetter;
#property (weak, nonatomic) id<LetterClickDelegateProtocol> clickDelegate;
#property (strong, nonatomic) UIButton *lblChar;
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength;
#end
LettersView.m
#import "LettersView.h"
#import "config.h"
#implementation LettersView{
NSInteger _xOffset, _yOffset;
}
- (id)initWithFrame:(CGRect)frame
{
NSAssert(NO, #"Use initWithLetter:andSideLength instead");
return nil;
}
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength
{
//the letter background
UIImage* img = [UIImage imageNamed:#"btn_letter#2x.png"];
//create a new object
self = [super initWithImage:img];
if (self != nil) {
//resize the letters
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0,0,img.size.width*scale, img.size.height*scale);
UIButton *lblChar = [[UIButton alloc] initWithFrame:self.bounds];
lblChar.tintColor = [UIColor blackColor];
lblChar.backgroundColor = [UIColor clearColor];
[lblChar setTitle:letter forState:UIControlStateNormal];
[lblChar addTarget:self action:#selector(displaychar:)forControlEvents:UIControlEventTouchUpInside];
[self addSubview:lblChar];
self.isMatched = NO;
_letter = letter;
self.userInteractionEnabled = YES;
}
return self;
}
-(void)displayChar:(id)sender {
UIButton *lblChar = (UIButton *)sender;
NSLog(#" The button's title is %#.", lblChar.currentTitle);
_clickLetter = lblChar.currentTitle;
if (self.clickDelegate) {
[self.clickDelegate letterView:self addChar:lblChar.currentTitle];
}
NSLog(#"hu %#", _clickLetter);
}
PlacesView.h
// PlacesView.m
#import "PlacesView.h"
#import "config.h"
#implementation PlacesView
-(id)initWithFrame:(CGRect)frame {
NSAssert(NO, #"Use initwithletter");
return nil;
}
-(instancetype)initWithLetter:(NSString *)letter andSideLength:(float)sideLength
{
UIImage *img = [UIImage imageNamed:#"btn_input#2x.png"];
self = [super initWithImage: img];
if (self != nil) {
self.isMatched = NO;
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0, 0, img.size.width*scale, img.size.height*scale);
//bullshit time
_fieldForLetter = [[UILabel alloc] initWithFrame:self.bounds];
_fieldForLetter.textAlignment = NSTextAlignmentCenter;
_fieldForLetter.textColor = [UIColor blackColor];
_fieldForLetter.backgroundColor = [UIColor clearColor];
_fieldForLetter.text = #"*"; // if button pressed button title placed here.
[self addSubview:_fieldForLetter];
_letter = letter;
}
return self;
}
#end
GameController.m
#import "GameController.h"
#import "config.h"
#import "LettersView.h"
#import "PlacesView.h"
#import "AppDelegate.h"
#implementation GameController {
//tile lists
NSMutableArray* _letters;
NSMutableArray* _places;
}
-(instancetype)init {
self = [super init];
if (self != nil) {
self.points = [[PointsController alloc] init];
self.audioController = [[AudioController alloc] init];
[self.audioController preloadAudioEffects: kAudioEffectFiles];
}
return self;
}
-(void)dealRandomWord {
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
_helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %#" , word1 , word2);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
//calculate the letter size
float letterSide = ceilf( kScreenWidth*0.9 / (float)MAX(word1len, word2len) ) - kTileMargin;
//get the left margin for first letter
float xOffset = (kScreenWidth - MAX(word1len, word2len) * (letterSide + kTileMargin))/2;
//adjust for letter center
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
// init places list
_places = [NSMutableArray arrayWithCapacity: word1len];
// create places
for (NSInteger i = 0; i<word1len; i++){
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
PlacesView* place = [[PlacesView alloc] initWithLetter:letter andSideLength:letterSide];
place.center = CGPointMake(xOffset + i*(letterSide + kTileMargin), kScreenHeight/4);
[self.gameView addSubview:place];
[_places addObject: place];
}
}
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
LettersView* letv = [[LettersView alloc] initWithLetter:letter andSideLength:letterSide];
letv.center = CGPointMake(xOffset + i * (letterSide + kTileMargin), kScreenHeight); // "/3*4"
if (i > 6) {
letv.center = CGPointMake(-5.15 * xOffset + i * (letterSide + kTileMargin), kScreenHeight + yOffset); // "/3*4"
}
letv.clickDelegate = self;
[self.gameView addSubview:letv];
[_letters addObject: letter];
}
}
}
-(void)letterView:(LettersView *)letterView addChar:(NSString *)addChar
{
PlacesView* placesView = nil;
for (PlacesView* pl in _places) {
//if (CGRectContainsPoint(pl.frame, pt)) {
if () {
//placesView = pl;
placesView.fieldForLetter.text = letterView.lblChar.currentTitle;
break;
}
}
//1 check if target was found
if (placesView!=nil) {
//2 check if letter matches
if ([placesView.letter isEqualToString: letterView.letter]) {
[self placeLetter:letterView atTarget:placesView];
[self.audioController playEffect: kSoundLetterTap];
self.points.points += self.level.coinsPerLvl; //ne nado tak
NSLog(#"Current points %d" , self.points.points);
[self checkForSuccess];
} else {
[self.audioController playEffect:kSoundFail];
[self addAlert:#"ne success" andMessage:#"You lose!" andButton:#"eshe cyka"];
}
}
}
-(void)placeLetter:(LettersView*)letterView atTarget:(PlacesView*)placeView {
placeView.isMatched = YES;
letterView.isMatched = YES;
letterView.userInteractionEnabled = NO;
}
-(void)checkForSuccess {
for (PlacesView* p in _places) {
//no success, bail out
if (p.isMatched==NO) return;
}
NSLog(#"ya!");
[self addAlert:#"Success" andMessage:#"You win!" andButton:#"eshe cyka"];
[self.audioController playEffect:kSoundSuccess];
}
-(void)addAlert: (NSString *)addTitle andMessage: (NSString *)alertMessage andButton: (NSString *)alertButton {
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.rootViewController = [UIViewController new];
window.windowLevel = UIWindowLevelAlert + 1;
UIAlertController *alert = [UIAlertController alertControllerWithTitle: addTitle message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction= [UIAlertAction actionWithTitle:alertButton style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
window.hidden = YES;
}];
[alert addAction:defaultAction];
[window makeKeyAndVisible];
[window.rootViewController presentViewController:alert animated:YES completion:nil];
});
}
#end
Your GameController needs to keep a reference to PlacesView. It can also assign the action into LettersView so when the button in LettersView is pressed, the GameController will fetch it and perform an action in PlacesView. GameController is what both the other classes have in common, so it can handle any actions between them.
Another option is to use NSNotificationCenter and post a message in LettersView when the button is pressed, and listen for it in PlacesView.
Yet anther way is using a delegates where GameController makes sure that PlacesView is set as the delegate. When LettersView's button is pressed, it will call the delegate method which PlacesView listens to.
I'd go with first option.
I'm trying to build an iOS Today Extension that shows three images with some text. In the simulator it runs fine, but when I run it on my iPhone, it flashes three times and then displays Unable to Load. What am I doing wrong?
TodayViewController.m
#import "TodayViewController.h"
#import <NotificationCenter/NotificationCenter.h>
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#interface TodayViewController () <NCWidgetProviding>
#property (strong, nonatomic) UILabel *descriptionLabel;
#property (strong, nonatomic) UIImageView *firstImage;
#property (strong, nonatomic) UIImageView *secondImage;
#property (strong, nonatomic) UIImageView *thirdImage;
#property (strong, nonatomic) UILabel *firstImageLabel;
#property (strong, nonatomic) UILabel *secondImageLabel;
#property (strong, nonatomic) UILabel *thirdImageLabel;
#property (strong, nonatomic) UILabel *firstImageOwnerLabel;
#property (strong, nonatomic) UILabel *secondImageOwnerLabel;
#property (strong, nonatomic) UILabel *thirdImageOwnerLabel;
#property (strong, nonatomic) NSDictionary *dataOne;
#property (strong, nonatomic) NSDictionary *dataTwo;
#property (strong, nonatomic) NSDictionary *dataThree;
#property (nonatomic) NSInteger quarterSize;
#property (nonatomic) NSInteger eightSize;
#end
#implementation TodayViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.preferredContentSize = CGSizeMake(self.view.frame.size.width, 320);
[self updateNumberLabelText];
if ([self.dataOne count] == 0) {
UILabel *noContent = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2)-150, 93, 300, 44)];
noContent.text = #"You haven't opened the app yet.";
[self.view addSubview:noContent];
} else {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"] || [deviceType isEqualToString:#"iPhone Simulator"])
{
self.quarterSize = self.view.frame.size.width/4;
self.eightSize = self.quarterSize/4;
} else if([deviceType isEqualToString:#"iPad"] || [deviceType isEqualToString:#"iPad Simulator"])
{
self.quarterSize = self.view.frame.size.width/5;
self.eightSize = self.quarterSize/4;
}
self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.eightSize, 15, self.view.frame.size.width-self.quarterSize, 20)];
self.descriptionLabel.text = #"Some new images just for you!";
self.descriptionLabel.textColor = [UIColor whiteColor];
[self.view addSubview:self.descriptionLabel];
UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(self.eightSize, 45, self.quarterSize, self.quarterSize*2)];
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(openFirstImage:)];
[firstView addGestureRecognizer:singleFingerTap];
if ([[self.dataOne objectForKey:#"imageurl"] isEqualToString:#"empty"]) {
UIView *noImageOne = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
noImageOne.backgroundColor = [self paperColorLightBlue500];
[firstView addSubview:noImageOne];
} else {
self.firstImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = self.firstImage;
[self.firstImage sd_setImageWithURL: [NSURL URLWithString:[self.dataOne objectForKey:#"imageurl"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}];
self.firstImage.contentMode = UIViewContentModeScaleAspectFill;
[self.firstImage setClipsToBounds:YES];
[firstView addSubview:self.firstImage];
}
UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(firstView.frame.origin.x + firstView.frame.size.width + self.eightSize, 45, self.quarterSize, self.quarterSize*2)];
UITapGestureRecognizer *secondFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(openSecondImage:)];
[secondView addGestureRecognizer:secondFingerTap];
if ([[self.dataTwo objectForKey:#"imageurl"] isEqualToString:#"empty"]) {
UIView *noImageTwo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
noImageTwo.backgroundColor = [self paperColorLightBlue500];
[secondView addSubview:noImageTwo];
} else {
self.secondImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = self.secondImage;
[self.secondImage sd_setImageWithURL: [NSURL URLWithString:[self.dataTwo objectForKey:#"imageurl"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}];
self.secondImage.contentMode = UIViewContentModeScaleAspectFill;
[self.secondImage setClipsToBounds:YES];
[secondView addSubview:self.secondImage];
}
UIView *thirdView = [[UIView alloc] initWithFrame:CGRectMake(secondView.frame.origin.x + secondView.frame.size.width + self.eightSize, 45, self.quarterSize, self.quarterSize*2)];
UITapGestureRecognizer *thirdFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(openThirdImage:)];
[thirdView addGestureRecognizer:thirdFingerTap];
if ([[self.dataThree objectForKey:#"imageurl"] isEqualToString:#"empty"]) {
UIView *noImageThird = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
noImageThird.backgroundColor = [self paperColorLightBlue500];
[thirdView addSubview:noImageThird];
} else {
self.thirdImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.quarterSize, self.quarterSize*1.25)];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = self.thirdImage;
[self.thirdImage sd_setImageWithURL: [NSURL URLWithString:[self.dataThree objectForKey:#"imageurl"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}];
self.thirdImage.contentMode = UIViewContentModeScaleAspectFill;
[self.thirdImage setClipsToBounds:YES];
[thirdView addSubview:self.thirdImage];
}
self.firstImageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImage.frame.origin.y + self.firstImage.frame.size.height + 10, self.quarterSize, 20)];
self.firstImageLabel.text = [self.dataOne objectForKey:#"title"];
self.firstImageLabel.numberOfLines = 2;
self.firstImageLabel.textColor = [UIColor whiteColor];
self.firstImageLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:13];
[self.firstImageLabel sizeToFit];
[firstView addSubview:self.firstImageLabel];
self.secondImageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImage.frame.origin.y + self.firstImage.frame.size.height + 10, self.quarterSize, 20)];
self.secondImageLabel.text = [self.dataTwo objectForKey:#"title"];
self.secondImageLabel.numberOfLines = 2;
self.secondImageLabel.textColor = [UIColor whiteColor];
self.secondImageLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:13];
[self.secondImageLabel sizeToFit];
[secondView addSubview:self.secondImageLabel];
self.thirdImageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImagele.frame.origin.y + self.firstImage.frame.size.height + 10, self.quarterSize, 20)];
self.thirdImageLabel.text = [self.dataThree objectForKey:#"title"];
self.thirdImageLabel.numberOfLines = 2;
self.thirdImageLabel.textColor = [UIColor whiteColor];
self.thirdImageLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:13];
[self.thirdImageLabel sizeToFit];
[thirdView addSubview:self.thirdImageLabel];
self.firstImageOwnerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImageLabel.frame.origin.y + self.firstImageLabel.frame.size.height, self.quarterSize, 30)];
self.firstImageOwnerLabel.text = [self.dataOne objectForKey:#"owner"];
self.firstImageOwnerLabel.numberOfLines = 1;
self.firstImageOwnerLabel.textColor = [UIColor lightGrayColor];
self.firstImageOwnerLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:11];
[firstView addSubview:self.firstImageOwnerLabel];
[self.view addSubview:firstView];
self.secondImageOwnerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImageLabel.frame.origin.y + self.firstImageLabel.frame.size.height, self.quarterSize, 30)];
self.secondImageOwnerLabel.text = [self.dataTwo objectForKey:#"owner"];
self.secondImageOwnerLabel.numberOfLines = 1;
self.secondImageOwnerLabel.textColor = [UIColor lightGrayColor];
self.secondImageOwnerLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:11];
[secondView addSubview:self.secondImageOwnerLabel];
[self.view addSubview:secondView];
self.thirdImageOwnerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.firstImageLabel.frame.origin.y + self.firstImageLabel.frame.size.height, self.quarterSize, 30)];
self.thirdImageOwnerLabel.text = [self.dataThree objectForKey:#"owner"];
self.thirdImageOwnerLabel.numberOfLines = 1;
self.thirdImageOwnerLabel.textColor = [UIColor lightGrayColor];
self.thirdImageOwnerLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:11];
[thirdView addSubview:self.thirdImageOwnerLabel];
[self.view addSubview:thirdView];
}
}
- (UIColor *)paperColorLightBlue500 { return UIColorFromRGB(0x03a9f4); }
- (void)openFirstImage:(UITapGestureRecognizer *)recognizer {
NSLog(#"Please open the First Image");
}
- (void)openSecondImage:(UITapGestureRecognizer *)recognizer {
NSLog(#"Please open the Second Image");
}
- (void)openThirdImage:(UITapGestureRecognizer *)recognizer {
NSLog(#"Please open the Third Image");
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
}
return self;
}
- (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets
{
return UIEdgeInsetsZero;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
self.firstImageLabel = nil;
self.secondImageLabel = nil;
self.thirdImageLabel = nil;
self.firstImageOwnerLabel = nil;
self.secondImageOwnerLabel = nil;
self.thirdImageOwnerLabel = nil;
}
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResultFailed
// If there's no update required, use NCUpdateResultNoData
// If there's an update, use NCUpdateResultNewData
completionHandler(NCUpdateResultNewData);
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
[self updateNumberLabelText];
}
- (void)updateNumberLabelText {
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:#"group.testapp.TodayExtensionDefaults"];
self.dataOne = [defaults objectForKey:#"dataOne"];
self.dataTwo = [defaults objectForKey:#"dataTwo"];
self.dataThree = [defaults objectForKey:#"dataThree"];
for (id key in self.dataOne) {
NSLog(#"key: %#, value: %# \n", key, [self.dataOne objectForKey:key]);
}
for (id key in self.dataThree) {
NSLog(#"key: %#, value: %# \n", key, [self.dataThree objectForKey:key]);
}
}
#end
The only error I get is that the Extension is Terminated due to Memory Error.
Extensions have much lower memory limits than normal apps. You'll have to investigate why you extension is using so much memory. Perhaps there's a leak.
I have a loading view that I insert over the top of a view while it is parsing data from the internet using a separate thread, in this case its on top of a UICollectionView.
For some reason that I cannot understand the loading overlay disappears on its own whist the parsing is still taking place, presenting a blank screen for a second or two. It doesn't seem to happen on UITableViews just on UIcollectionviews. Any help would be appreciated.
Activity overlay.m:
#import "ActivityOverlayController.h
#interface ActivityOverlayController ()
#end
#implementation ActivityOverlayController
-(id)initWithFrame:(CGRect)theFrame {
if (self = [super init]) {
frame = theFrame;
self.view.frame = theFrame;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", #"ActivityOverlayController called");
container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
activityLabel = [[UILabel alloc] init];
activityLabel.text = NSLocalizedString(#"Loading", #"string1");
activityLabel.textColor = [UIColor lightGrayColor];
activityLabel.font = [UIFont boldSystemFontOfSize:17];
[container addSubview:activityLabel];
activityLabel.frame = CGRectMake(0, 3, 70, 25);
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.color = [UIColor blackColor];
activityIndicator.hidesWhenStopped = TRUE;
[activityIndicator startAnimating];
activityIndicator.frame = CGRectMake(80, 0, 30, 30);
[container addSubview:activityIndicator];
[self.view addSubview:container];
container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
self.view.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.7];
}
-(void)viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[activityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Parsing part of collectionViewController.m:
-(void)ParseCollectionView{
[self performSelectorOnMainThread:#selector(showActivityView) withObject:nil waitUntilDone:YES];
CollectionViewImages = [[NSMutableArray alloc]init];
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:GalleryTitle]];
cvTBXML = [[TBXML alloc]initWithXMLData:xmlData];
// Obtain root element
TBXMLElement * root = cvTBXML.rootXMLElement;
TBXMLElement * channel = [TBXML childElementNamed:#"channel" parentElement:root];
if (root)
{
TBXMLElement * item = [TBXML childElementNamed:#"item" parentElement:channel];
while (item !=nil)
{
//create new instance of news object
NSObject *Imagetoparse = [[GalleryImage alloc] init];
TBXMLElement * link = [TBXML childElementNamed:#"link" parentElement:item];
NSString *linktext= [TBXML textForElement:link];
[Imagetoparse setValue:linktext forKey:#"link"];
TBXMLElement * thumbnail = [TBXML childElementNamed:#"description" parentElement:item];
NSString *Thumbnailtext= [TBXML textForElement:thumbnail];
Thumbnailtext = [Thumbnailtext substringFromIndex:21];
NSInteger *slength = Thumbnailtext.length -4;
Thumbnailtext = [Thumbnailtext substringToIndex:slength];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#"thumb" withString:#"main"];
NSLog(#"Thumnail1 : %#", Thumbnailtext);
NSData *Thumbnailimage = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: Thumbnailtext]];
[Imagetoparse setValue:Thumbnailimage forKey:#"thumbnail"];
[CollectionViewImages addObject:Imagetoparse];
item = [TBXML nextSiblingNamed:#"item" searchFromElement:item];
}
}
[self.collectionView reloadData];
NSLog(#"%#", #"Finished Parse Collection View");
[self performSelectorOnMainThread:#selector(hideActivityView) withObject:nil waitUntilDone:NO];
}
-(void)showActivityView {
if (overlayController == nil) {
overlayController = [[ActivityOverlayController alloc] initWithFrame:(self.view.superview.bounds)];
}
[self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
-(void)hideActivityView {
[overlayController.view removeFromSuperview];
}
Hello friends i am uploading my code from last few days on the stackoverflow but somwhow i am not getting the thing which i want. Noe once again i am trying this please try to help me out and solve my proplems. Firstly see the code.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
#interface welcomemapViewController : UIViewController
#property (strong, nonatomic) UITextField *txt;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "welcomemapViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kLatestSearchURL [NSURL URLWithString: #"https://maps.googleapis.com/maps/api/place/textsearch/xml?query=Delhi&sensor=true&key=Your API key"]
#interface welcomemapViewController ()
#end
#implementation welcomemapViewController
{
GMSMapView *gmap;
}
#synthesize txt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
GMSCameraPosition *cam = [GMSCameraPosition cameraWithLatitude:30.7343000 longitude:76.7933000 zoom:12];
gmap = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:cam];
gmap.myLocationEnabled = YES;
gmap.mapType = kGMSTypeHybrid;
gmap.settings.myLocationButton = YES;
gmap.settings.zoomGestures = YES;
gmap.settings.tiltGestures = NO;
gmap.settings.rotateGestures = YES;
[self.view addSubview:gmap];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(30.751288, 76.780899);
marker.title = #"Sector -16";
marker.snippet = #"Chandigarh";
marker.map = gmap;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(200, 65, 100, 40);
[button setTitle:#"SEARCH" forState:UIControlStateNormal];
[button addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
CGRect frame2 = CGRectMake(10, 68, 200, 30);
txt =[[UITextField alloc]initWithFrame:frame2];
txt.placeholder = #"Search";
txt.userInteractionEnabled = YES;
txt.keyboardType = UIKeyboardTypeAlphabet;
[txt setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:txt];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSString *data1 = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"Response data: %#", data1);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* responseResults = [json objectForKey:#"results"];
NSLog(#"Locations are %#", responseResults);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
now in "NSLog(#"Locations are %#", responseResults);" i am getting my values, i simply want to add these values onto the map in the form of pointers with details.
So kindly help me how it should be done. (And kindly help me with the help of codes)
you can do this by using MKPointAnnotation and then add this MKPointAnnotation in you mapview
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = #"your Latitude to point on map";
annotationCoord.longitude = #"your Longitude to point on map";;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = #"your title";
annotationPoint.subtitle = #"your subtitle";
[YourmapView addAnnotation:annotationPoint];