I'm reading "beginning iPad application development", and at the bluetooth chapter i'm testing the code exactly as it appears at the book. The only difference is that the book was for 3.2 and I'm using XCODE 4 for iOS >4.0.
XCODE does not throw any error or warning, it builds correctly, but when testing at the iPhone it doesn't discover other devices.
What's wrong?
The viewController.h looks like:
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
#interface pruebaBluetoothViewController : UIViewController
<GKSessionDelegate, GKPeerPickerControllerDelegate> {
GKSession *currentSession;
IBOutlet UITextField *txtMessage;
IBOutlet UIButton *connect;
IBOutlet UIButton *disconnect;
GKPeerPickerController *picker;
}
#property (nonatomic, retain) GKSession *currentSession;
#property (nonatomic, retain) UITextField *txtMessage;
#property (nonatomic, retain) UIButton *connect;
#property (nonatomic, retain) UIButton *disconnect;
-(IBAction) btnSend:(id) sender;
-(IBAction) btnConnect:(id) sender;
-(IBAction) btnDisconnect:(id) sender;
#end
While the .m looks like:
#import "pruebaBluetoothViewController.h"
#implementation pruebaBluetoothViewController
#synthesize currentSession;
#synthesize txtMessage;
#synthesize connect;
#synthesize disconnect;
- (void)viewDidLoad {
[connect setHidden:NO];
[disconnect setHidden:YES];
[super viewDidLoad];
}
-(IBAction) btnConnect:(id) sender {
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self;
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[connect setHidden:YES];
[disconnect setHidden:NO];
[picker show];
}
- (void)peerPickerController:(GKPeerPickerController *)pk
didConnectPeer:(NSString *)peerID
toSession:(GKSession *) session {
self.currentSession = session;
session.delegate = self;
[session setDataReceiveHandler:self withContext:nil];
picker.delegate = nil;
[picker dismiss];
[picker autorelease];
}
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)pk {
picker.delegate = nil;
[picker autorelease];
[connect setHidden:NO];
[disconnect setHidden:YES];
}
-(IBAction) btnDisconnect:(id) sender {
[self.currentSession disconnectFromAllPeers];
[self.currentSession release];
currentSession = nil;
[connect setHidden:NO];
[disconnect setHidden:YES];
}
- (void)session:(GKSession *)session
peer:(NSString *)peerID
didChangeState:(GKPeerConnectionState)state {
switch (state) {
case GKPeerStateConnected:
NSLog(#"connected");
break;
case GKPeerStateDisconnected:
NSLog(#"disconnected");
[self.currentSession release];
currentSession = nil;
[connect setHidden:NO];
[disconnect setHidden:YES];
break;
}
}
- (void)dealloc {
[txtMessage release];
[currentSession release];
[super dealloc];
}
- (void) mySendDataToPeers:(NSData *) data {
if (currentSession)
[self.currentSession sendDataToAllPeers:data
withDataMode:GKSendDataReliable
error:nil];
}
-(IBAction) btnSend:(id) sender {
//---convert an NSString object to NSData---
NSData* data;
NSString *str = [NSString stringWithString:txtMessage.text];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
- (void) receiveData:(NSData *)data
fromPeer:(NSString *)peer
inSession:(GKSession *)session
context:(void *)context {
//---convert the NSData to NSString---
NSString* str;
str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Data received"
message:str
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
looks like you missed the following Delegate Method:
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type {
GKSession *session = [[GKSession alloc] initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModePeer];
return [session autorelease]; // peer picker retains a reference, so autorelease ours so we don't leak.
}
Hope this helps.
Related
I am developing AVAudioPlayer according to my project requirement. In audioplayer iam using storyboard to develope coding.In my audio player using json parser to retrieve the urls from server.And finally gave the connections from first responder to Audioviewcontroller.I Can run the audioplayer. Audioplayer is successfully playing. But view will not be displayed.Blank screen will be displayed. I can drag and drop of all buttons like play button, pause button,forward button and rewind button etc. Those are buttons are drag and drop on AudioviewController. And give the connections also.These are all buttons are not displayed on Audioviewcontroller to play the corresponding song. Plz help me any body whats the problem. I am new to the ios programming.Thanks in Advance...
Audioviewcontroller.m
-(void)updateCurrentTimeForPlayer:(AVAudioPlayer *)
{
currentTime.text = [NSString stringWithFormat:#"%d:%02d", (int)p.currentTime / 60, (int)p.currentTime % 60, nil];
progressBar.value = p.currentTime;
}
-(void)updateCurrentTime
{
[self updateCurrentTimeForPlayer:self.avPlayer];
}
-(void)updateViewForPlayerState:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (updateTimer)
[updateTimer invalidate];
if (p.playing)
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
updateTimer=[NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(updateCurrentTime) userInfo:p repeats:YES];
}
else
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
updateTimer=nil;
}
}
-(void)updateViewForPlayerStateInBackground:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (p.playing)
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
}
else
{
[playButton setImage:(p.playing==YES)? pauseButtonBG:playButtonBG forState:UIControlStateNormal];
}
}
-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p
{
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)p.duration / 60, (int)p.duration % 60, nil];
progressBar.maximumValue = p.duration;
volumeSlider.value = p.volume;
}
// rewind audio player
-(void)rewind
{
AVAudioPlayer *p=rewindTimer.userInfo;
p.currentTime-=SKIP_TIME;
[self updateCurrentTimeForPlayer:p];
}
// forward audio player
-(void)forward
{
AVAudioPlayer *p=forwardTimer.userInfo;
p.currentTime+=SKIP_INTERVAL;
[self updateCurrentTimeForPlayer:p];
}
json parser::
-(void)loadData
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.teluguastrology.com"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// delegate methods in json
-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response
{
[_data setLength:0];
NSLog(#"didReceiveResponse called");
}
//connection did receive data
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data
{
[_data appendData:data];
}
// connection did finish loading
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:_data options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]])
{
//NSArray *jsonArray = (NSArray *)jsonObject;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSArray *array=[[NSArray alloc]init];
array=[jsonDictionary objectForKey:#"audio-urls"];
dataDictionary=[array objectAtIndex:0];
/* NSLog(#"%#",dataDictionary);*/
}
[urlsArray addObject:[dataDictionary objectForKey:#"Meshamu-Aries"]];
NSLog(#"%#",urlsArray);
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// [connection release];
NSLog(#"didFailWithError called");
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
// self.view.backgroundColor=[UIColor redColor];
urlsArray=[[NSMutableArray alloc]init];
[super viewDidLoad];
playButtonBG=[[UIImage imageNamed:#"audio_play.png"]init];
pauseButtonBG=[[UIImage imageNamed:#"audio_pause.png"]init];
[playButton setImage:playButtonBG forState:UIControlStateNormal];
//[self registerForBackGroundNotification];
updateTimer=nil;
rewindTimer=nil;
forwardTimer=nil;
// to adjust the font in label to using following method
duration.adjustsFontSizeToFitWidth=YES;
currentTime.adjustsFontSizeToFitWidth=YES;
progressBar.minimumValue=0.0;
_data=[[NSMutableData alloc]init];
[self loadData];
backgroundImg=[[UIImageView alloc]init];
backgroundImg.image=[UIImage imageNamed:#"image.png"];
[self.view addSubview:backgroundImg];
}
-(void)pausePlaybackForPlayer:(AVAudioPlayer *)p
{
[p pause];
[self updateViewForPlayerState:p];
}
-(void)startPlaybackForPlayer:(AVAudioPlayer *)p
{
if([p play])
{
[self updateViewForPlayerState:p];
}
else
NSLog(#"Could not play %#\n", p.url);
}
-(IBAction)playButtonPressed:(UIButton *)sender
{
if (avPlayer.playing==YES)
[self pausePlaybackForPlayer:avPlayer];
else
[self startPlaybackForPlayer:avPlayer];
}
-(IBAction)rewindButtonPressed:(UIButton *)sender
{
if(rewindTimer)
[rewindTimer invalidate];
rewindTimer=[NSTimer scheduledTimerWithTimeInterval:SKIP_INTERVAL target:self selector:#selector(rewind) userInfo:avPlayer repeats:YES];
}
-(IBAction)rewindButtonReleased:(UIButton *)sender
{
if(rewindTimer)
[rewindTimer invalidate];
rewindTimer=nil;
}
-(IBAction)forwardButtonPressed:(UIButton *)sender
{
if(forwardTimer)
[forwardTimer invalidate];
forwardTimer=[NSTimer scheduledTimerWithTimeInterval:SKIP_TIME target:self selector:#selector(forward) userInfo:avPlayer repeats:YES];
}
-(IBAction)forwardButtonReleased:(UIButton *)sender
{
if(forwardTimer)
[forwardTimer invalidate];
forwardTimer=nil;
}
-(IBAction)volumeSliderMoved:(UISlider *)sender
{
avPlayer.volume=[sender value];
}
-(IBAction)progressBarMoved:(UISlider *)sender
{
avPlayer.currentTime=[sender value];
[self updateCurrentTimeForPlayer:avPlayer];
}
Audioviewcontroller.h
#interface AudioViewController : UIViewController<AVAudioPlayerDelegate,NSURLConnectionDelegate>
{
IBOutlet UILabel *astroName;
IBOutlet UIButton *playButton;
IBOutlet UIButton *forwardButton;
IBOutlet UIButton *rewindButton;
IBOutlet UISlider *volumeSlider;
IBOutlet UILabel *currentTime;
IBOutlet UILabel *duration;
IBOutlet UISlider *progressBar;
UIImage *playButtonBG;
UIImage *pauseButtonBG;
NSTimer *forwardTimer;
NSTimer *rewindTimer;
NSTimer *updateTimer;
UIImageView *backgroundImg;
BOOL inBackground;
NSURLConnection *connect;
NSMutableData *responseData;
NSMutableData *downloadData;
NSMutableString *responseString;
NSMutableArray *urlsArray;
NSMutableData *_data;
NSDictionary *dataDictionary;
}
- (IBAction)playButtonPressed:(UIButton*)sender;
- (IBAction)rewindButtonPressed:(UIButton*)sender;
- (IBAction)rewindButtonReleased:(UIButton*)sender;
- (IBAction)forwardButtonPressed:(UIButton*)sender;
- (IBAction)forwardButtonReleased:(UIButton*)sender;
- (IBAction)volumeSliderMoved:(UISlider*)sender;
-(IBAction)progressBarMoved:(UISlider *)sender;
-(void)registerForBackGroundNotification;
#property(nonatomic,retain) UILabel *astroName;
#property(nonatomic,retain) UIButton *playButton;
#property(nonatomic,retain) UIButton *pauseButton;
#property(nonatomic,retain) UIButton *forwardButton;
#property(nonatomic,retain) UIButton *rewindButton;
#property(nonatomic,retain) UISlider *volumeSlider;
#property(nonatomic,retain) UISlider *progressBar;
#property(nonatomic,retain) UILabel *currentTime;
#property(nonatomic,retain) UILabel *duration;
#property(nonatomic,retain) NSTimer *updateTimer;
#property(nonatomic,retain) AVAudioPlayer *avPlayer;
#property(nonatomic,assign) BOOL *inBackGround;
#property(nonatomic,retain) UIImageView *backgroundImg;
#property(retain, nonatomic) NSMutableData* responseData;
#property(nonatomic,strong) NSData *downloadData;
#property(nonatomic,strong) NSMutableString *responseString;
#property (nonatomic,assign)int selectedIndex;
#end
Just try to comment this line of code. You have added UIImageView to self.view after adding all button. Please add this by using storyboard.
//[self.view addSubview:backgroundImg];
Good Luck !!
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Please do not close this topic.I really need help.
I am developing on IOS 6.Xcode-4.5.2
On a button click i get the below xml data from the server
<country>america</country>
<dateOfBirth xsi:nil="true"/>
<firstName>John</firstName>
<lastName>Smith</lastName>
<userEmail>johnsmith#email.com</userEmail>
I am trying to parse it and get the values.I did as per the example shown in this url http://www.edumobile.org/iphone/iphone-programming-tutorials/parsing-an-xml-file/
But i am getting an error when the parse method is called.
Instead of the appdelegate class as shown in the example url i am using the viewcontroller class.I do not want to add any code in the Appdelegate class.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate setUserDetails:]: unrecognized selector sent to instance 0x9272a40'
I am just a beginner in iphone programming.So i need help in parsing this successfully and i just want to get the values somehow so that i can use them to show on screen in some labels.
Below are codes for 6 files(Viewcontroller.h & m,User.h & m,Xmlparser.h & m)
//ViewController.h
#import <UIKit/UIKit.h>
#import "GlobalVariable.h"
#import "QuotesViewController.h"
#interface ViewController : UIViewController <NSXMLParserDelegate,UIApplicationDelegate,NSStreamDelegate,UIAlertViewDelegate,WriteProtocol>
{
QuotesViewController *quoteobj;
NSMutableArray *userDetails;
}
#property (retain, nonatomic) IBOutlet UITextField *txtUsername;
#property (retain, nonatomic) IBOutlet UITextField *txtPassword;
#property (retain, nonatomic) NSInputStream *inputStream;
#property (retain, nonatomic) NSOutputStream *outputStream;
#property (nonatomic, retain) NSMutableArray *messages;
#property (retain, nonatomic) IBOutlet UILabel *label1;
- (IBAction)btnLogin:(id)sender;
- (IBAction)btnExit:(id)sender;
- (void)initNetworkCommunication;
- (void)readIn:(NSString *)s;
- (void)writeOut:(NSString *)s;
#property (nonatomic, retain) NSMutableArray *userDetails;
#end
//ViewController.m
#import "ViewController.h"
#import "NewTabViewController.h"
#import "QuotesViewController.h"
#import "XMLParser.h"
#implementation ViewController
#synthesize txtPassword,txtUsername,inputStream, outputStream,messages,label1,userDetails;
- (void)viewDidLoad
{
[super viewDidLoad];
quoteobj =[[QuotesViewController alloc]init];
quoteobj.myTableView = [[UITableView alloc]init];
quoteobj.myTableView.delegate=quoteobj;
quoteobj.myTableView.dataSource=quoteobj;
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)btnLogin:(id)sender {
NSLog(#"Clicked button1");
[self initNetworkCommunication];
NSString *response = [NSString stringWithFormat:#"POST\r\n\r\nTMS|Login|%#|%#",txtUsername.text,txtPassword.text];
NSLog(#"1");
[self writeOut:response];
}
- (IBAction)btnExit:(id)sender {
exit(0);
}
- (void) initNetworkCommunication {
NSLog(#"initNetworkCommunication called");
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"xxx.xxx.x.xx", xxxx, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream retain];
[outputStream retain];
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
[self readIn:output];
if([output hasPrefix:#"JSESSIONID"]){
int len = [output length];
int lenn = len-29;
sessionId = [output substringWithRange:NSMakeRange(0, lenn)];
label1.text=sessionId;
NSLog(#"New String %# LENGTH SESSUIn %i",sessionId,sessionId.length);
sessionId=label1.text;
NewTabViewController *so = [self.storyboard instantiateViewControllerWithIdentifier:#"newtab"];
for(UIViewController *ssa in so.viewControllers){
if([ssa isKindOfClass:[QuotesViewController class]]){
QuotesViewController *qq = (QuotesViewController *) ssa;
NSLog(#"PREESENTING THIS FZZZZZZZZZZZzzaaadfsdfssdfsa");
[qq setDel:self];
}
}
[self presentViewController:so animated:YES completion:nil];
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Server says.." message:#"Due to some reason server is unavailable" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
break;
case NSStreamEventEndEncountered:
NSLog(#"NSStreamEventEndEncountered:method is called");
[theStream close];
NSLog(#"theStream is closed");
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSLog(#"theStream is removed from runloop");
[theStream release];
NSLog(#"theStream is released");
NSLog(#"Server is unavailable");
theStream = nil;
if(theStream==nil){
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Server says.." message:#"Due to some reason server is unavailable" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
}
NSLog(#"IT reaches 1 here");
break;
default:
NSLog(#"Unknown event");
}
}//End of stream
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(#"IT reaches here");
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Ok"])
{
NSLog(#"Ok is clicked");
exit(0);
}
}
- (void) messageReceived:(NSString *)message {
NSLog(#"Entered MessageRecieved");
[messages addObject:message];
}
- (void)readIn:(NSString *)s {
NSLog(#"%#", s);
if ([s hasPrefix:#"{"]) {
if([s rangeOfString:#"instrSymbol"].location ==NSNotFound){
NSLog(#"Received a data which is not instrumentid");
}
else{
NSLog(#"JSON DATA RECEIVED");
[quoteobj parseJsonData:s];
}
}
else if([s hasPrefix:#"<"]){
NSLog(#"XML DATA RECEIVED");
NSData *xmlData= [[NSData alloc]initWithData:[s dataUsingEncoding:NSUTF8StringEncoding]];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
}
}
- (void)writeOut:(NSString *)s {
if (outputStream) {
NSLog(#"WRITING OUT");
uint8_t *buf = (uint8_t *)[s UTF8String];
[outputStream write:buf maxLength:strlen((char *)buf)];
NSLog(#"Writing out the following:");
NSLog(#"%#", s);
}
else{
NSLog(#"Noutoyt");
}
}
#end
//XMLParser.h
#import <Foundation/Foundation.h>
#class ViewController,User;
#interface XMLParser : NSObject{
NSMutableString *currentElementValue;
ViewController *zappDelegate;
User *aBook;
}
- (XMLParser *) initXMLParser;
#end
//XMLParser.m
#import "XMLParser.h"
#import "ViewController.h"
#import "User.h"
#implementation XMLParser
- (XMLParser *) initXMLParser {
[super init];
zappDelegate = (ViewController *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"country"]) {
//Initialize the array.
zappDelegate.userDetails = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:#"firstName"]) {
//Initialize the book.
aBook = [[User alloc] init];
//Extract the attribute here.
//aBook.bookID = [[attributeDict objectForKey:#"id"] integerValue];
//NSLog(#"Reading id value :%i", aBook.bookID);
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(#"Processing Value: %#", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"Books"])
return;
if([elementName isEqualToString:#"Book"]) {
[zappDelegate.userDetails addObject:aBook];
[aBook release];
aBook = nil;
}
else
[aBook setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
}
#end
//User.h
#import <Foundation/Foundation.h>
#interface User : NSObject {
//NSInteger bookID;
NSString *firstName; //Same name as the Entity Name.
NSString *lastName; //Same name as the Entity Name.
NSString *userEmail; //Same name as the Entity Name.
}
#property (nonatomic, retain) NSString *firstName;
#property (nonatomic, retain) NSString *lastName;
#property (nonatomic, retain) NSString *userEmail;
#end
//User.m
#import "User.h"
#implementation User
#synthesize firstName,lastName,userEmail;
- (void) dealloc {
[firstName release];
[lastName release];
[userEmail release];
[super dealloc];
}
#end
You created a class called ViewController but then you try assigning an instance of it in the XMLParser class by casting the application delegate which is unrelated.
zappDelegate = (ViewController *)[[UIApplication sharedApplication] delegate];
You need to change the name of zappDelegate to something more appropriate and assign it a real instance of your ViewController.
I do notice that your ViewController does conform to the UIApplicationDelegate protocol but that does not automatically make it the applications delegate. The real delegate should be properly setup in the main.m[m] file.
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
Check this link i modified the source :
http://dcraziee.wordpress.com/2013/05/29/parsing-xml-in-objective-c/
It will return you the dictionary from your xml response.
All the keys in your xml will be a key and value will in value part of dictionary.
If you contains hierarchal xml then will be managed accordingly.
I hope this will help.
I am making an Alarm clock in which i want that when the selected time through Datepicker occur instead of only notification and Badge occurance , I wanted to play my custom Sound file i.e. jet.wav (it is of less than 30 sec and in .wav format).i want that as soon as my notification occurs it should play a sound and when i click on the app or alert view then it should stop. So can anyone please help me out. here is what i am trying :-
Code:-
#class The420DudeViewController;
#interface The420DudeAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
The420DudeViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet The420DudeViewController *viewController;
extern NSString *kRemindMeNotificationDataKey;
#implementation The420DudeAppDelegate
#synthesize window;
#synthesize viewController;
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Class cls = NSClassFromString(#"UILocalNotification");
if (cls) {
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
[window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
#interface The420DudeViewController : UIViewController {
IBOutlet UINavigationBar *titleBar;
IBOutlet UIButton *setAlarmButton;
IBOutlet UIDatePicker *selectTimePicker;
AVAudioPlayer *player;
}
#property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
#property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
#property(nonatomic, retain) IBOutlet UIDatePicker *selectTimePicker;
-(IBAction)onTapSetAlarm;
- (void)showReminder:(NSString *)text;
#end
#implementation The420DudeViewController
#synthesize titleBar,setAlarmButton,selectTimePicker;
#pragma mark -
#pragma mark === Initialization and shutdown ===
#pragma mark -
- (void)viewDidLoad {
[super viewDidLoad];
selectTimePicker.minimumDate = [NSDate date];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.setAlarmButton = nil;
self.selectTimePicker = nil;
}
/*
-(void)viewWillAppear:(BOOL)animated
{
NSString *path = [[NSBundle mainBundle]pathForResource:#"Song1" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
// [player play];
}
*/
-(IBAction)onTapSetAlarm
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [selectTimePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Did you forget something?";
notif.alertAction = #"Show me";
notif.repeatInterval = NSDayCalendarUnit;
// notif.soundName = UILocalNotificationDefaultSoundName;
notif.soundName = [[NSBundle mainBundle]pathForResource:#"jet" ofType:#"wav"];
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"Mayank"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
/*
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm a"];
NSDate *selectedDate = [[NSDate alloc] init];
selectedDate = [selectTimePicker date];
NSString *theTime = [timeFormat stringFromDate:selectedDate];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Time selected" message:theTime delegate:nil cancelButtonTitle:#"YES" otherButtonTitles:nil];
[alert show];
[alert release];
// [timeFormat release];
// [selectedDate release];
*/
}
#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -
- (void)showReminder:(NSString *)text {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:#" TEXT " delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
- (void)dealloc {
[super dealloc];
[titleBar release];
[setAlarmButton release];
[selectTimePicker release];
}
#end
According to the documentation for soundName, you should
specify the filename (including extension) of a sound resource in the application’s main bundle
Thus I suggest you change this line of -[The420DudeViewController onTapSetAlarm]:
notif.soundName = [[NSBundle mainBundle]pathForResource:#"jet" ofType:#"wav"];
to the following:
notif.soundName = #"jet.wav";
Actually I have parsed an XML and store URL's of images as an NSMutableArray object, but I want this array to be used in another ViewController (to give to UIImage in UIImageView to show Images at runtime), so I am trying to copy that Mutable array to myAppDelegate_iPhone's NSMutableArray. And I want to again copy that Appdelegate's array to my next or other ViewControllers NSMutableArray.
so can anyone help me out pleaseeeeee? Here is my code :-
code:-
#class FirstViewController;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UIWindow *window;
FirstViewController *viewController;
NSMutableArray *logoArray;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) NSMutableArray *logoArray;
#end
#import "AppDelegate_iPhone.h"
#import "FirstViewController.h"
#import "ParsingViewController.h"
#implementation AppDelegate_iPhone
#synthesize window,logoArray;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
viewController = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
NSURL *url = [[NSURL alloc] initWithString:#"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
ParsingViewController *parser = [[ParsingViewController alloc] init];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
logoArray = [[NSMutableArray alloc]init];
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
// dealloc done
#end
#class Litofinter,AppDelegate_iPhone;
#interface ParsingViewController : NSObject<NSXMLParserDelegate> {
NSString *myString;
NSMutableArray *myMutableArray;
Litofinter *obj;
NSString *currentElement;
AppDelegate_iPhone *appDelegate;
}
#import "ParsingViewController.h"
#import "Litofinter.h"
#import "AppDelegate_iPhone.h"
#implementation ParsingViewController
#synthesize myMutableArray, myString;
-(id)init{
if(self == [super init]){
myMutableArray = [[NSMutableArray alloc] init];
}
return self;
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//myMutableArray = [[NSMutableArray alloc]init];
}
// Parsing done here
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
//UIApplication *app = [UIApplication sharedApplication];
//appDelegate=app.delegate;
appDelegate.logoArray = [[NSMutableArray alloc]initWithArray:myMutableArray];
NSLog(#"appDelegate.logoArray count %d",[appDelegate.logoArray count]);
for (Litofinter *lito in appDelegate.logoArray) {
NSLog(#"Array Elements :----- %#",lito.cLogo);
}
}
#end
#import <UIKit/UIKit.h>
#class AppDelegate_iPhone,Litofinter,ParsingViewController;
#interface FirstViewController : UIViewController {
NSMutableArray *array;
//Litofinter *lito;
NSString *logoString;
AppDelegate_iPhone *appDelegate;
ParsingViewController *obj;
}
#end
#import "FirstViewController.h"
#import "AppDelegate_iPhone.h"
#import "Litofinter.h"
#import "ParsingViewController.h"
#implementation FirstViewController
-(id)init{
if(self == [super init]){
obj = [[ParsingViewController alloc] init];
array = [[NSArray alloc] initWithArray: obj.myMutableArray];
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int x=5,y=10;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
// UIApplication *app = [UIApplication sharedApplication];
// appDelegate=app.delegate;
NSLog(#"delegate Array ====== %d",[appDelegate.logoArray count]);
NSLog(#"New Array ====== %d",[obj.myMutableArray count]);
/*
array = [[NSMutableArray alloc]initWithArray:appDelegate.logoArray];
NSLog(#"array at 0 ===== %#",[array objectAtIndex:0]);
for (Litofinter *lito1 in obj.myMutableArray) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito1.cLogo);
}
for (Litofinter *lito2 in array) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito2.cLogo);
}
*/
for (Litofinter *lito in obj.myMutableArray) {
//for (int i=0; i<[appDelegate.logoArray count]; i++) {
// lito.cLogo = [array objectAtIndex:i];
NSLog(#"%#",lito.cLogo);
UIImage *imageFromUrl = [UIImage imageWithContentsOfFile:[NSURL fileURLWithPath:lito.cLogo]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:imageFromUrl];
[imgView setFrame:CGRectMake(x, y, 196, 90)];
[self.view addSubview:imgView];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onTapImage)];
[imgView addGestureRecognizer:tgr];
// [tgr release];
//Do the rest of your operations here, don't forget to release the UIImageView
x = x + 200;
}
}
-(void)onTapImage
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Message from mAc" message:#"Trail" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
}
- (void)dealloc {
[super dealloc];
}
#end
You can use this.
UIImage *imageFromUrl = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:lito.cLogo]]];
I have an UIAlertView with a UITextField in it. I want to type the mail id and submit in UIAlertView's ok button, but UITextField in the UIAlertView have no response, Please help me.
thankz
From iOS 5 the approach above is no longer necessary. Just set the alertViewStyle property to the appropriate style (UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput, or UIAlertViewStyleLoginAndPasswordInput).
Example:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Email" message:#"Enter your email:" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];
and you can have the response back as
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UITextField *emailTextField = [alertView textFieldAtIndex:0];
NSLog(#"%#",emailTextField.text);
}
UIAlertView with UITextField:
Usage:
NSString *title = NSLocalizedString(#"Your Title","");
NSString *placeholder = NSLocalizedString(#"Placeholder Text","");
NSString *message = NSLocalizedString(#"A message to the user.","");
NSString *cancel = NSLocalizedString(#"Cancel","");
NSString *okay = NSLocalizedString(#"Continue","");
prompt = [[AlertPrompt alloc] initWithTitle:title
placeholder:placeholder
message:message
delegate:self
cancelButtonTitle:cancel
okButtonTitle:okay];
[prompt show];
[prompt release];
.h
#import <Foundation/Foundation.h>
#interface AlertPrompt : UIAlertView <UITextFieldDelegate>
{
UITextField *textField;
NSString *enteredText;
}
#property(nonatomic,retain) UITextField *textField;
#property (nonatomic, retain, readonly) NSString *enteredText;
- (id)initWithTitle:(NSString *)title placeholder:(NSString *)placeholder message:(NSString *)message delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okayButtonTitle;
#end
.m
#import ".h"
#implementation AlertPrompt
#synthesize textField;
#synthesize enteredText;
#pragma mark -
#pragma mark AlertPrompt Delegates
- (id)initWithTitle:(NSString *)title placeholder:(NSString *)placeholder message:(NSString *)message delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okayButtonTitle {
if (self = [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:okayButtonTitle, nil])
{
self.title = title;
self.message = [NSString stringWithFormat:#"%#\n\n\n",message];
self.delegate = delegate;
UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 75.0f, 260.0, 30.0)];
[theTextField setBackgroundColor:[UIColor clearColor]];
theTextField.borderStyle = UITextBorderStyleRoundedRect;
theTextField.textColor = [UIColor blackColor];
theTextField.font = [UIFont systemFontOfSize:18.0];
theTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
theTextField.keyboardAppearance = UIKeyboardAppearanceAlert;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
theTextField.placeholder = placeholder;
theTextField.delegate = self;
[self insertSubview:theTextField atIndex:0];
self.textField = theTextField;
[theTextField release];
CGAffineTransform translate = CGAffineTransformMakeTranslation(0, -10);
[self setTransform:translate];
}
return self;
}
- (void)show{
[textField becomeFirstResponder];
[super show];
}
- (NSString *)enteredText{
return textField.text;
}
- (void)dealloc{
[textField resignFirstResponder];
[textField release];
[super dealloc];
}
#end
Delegate:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.title isEqualToString:#"Your Title"])
{
if(buttonIndex == 1)
{
/* get the user iputted text */
NSString *inputValue = [(AlertPrompt *)alertView enteredText];
NSLog(#"User Input: %#",inputValue);
{
}
}
UIAlertView *emailAlert=[[UIAlertView alloc]initWithTitle:#"Enter your Email-id" message:#"\n\n" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
emailTextField=[[UITextField alloc]initWithFrame:CGRectMake(12,45,260,25)];
[emailTextField becomeFirstResponder];
[emailTextField setBackgroundColor:[UIColor whiteColor]];
emailTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
emailTextField.placeHolder=#"Email";
[emailAlert addSubview:emailTextField];
[emailAlert show];
[emailAlert release];
Use UIAlertView Delegates Methods when OK button is clicked.
Swift version:
var alert = UIAlertView(title: "PostActionTitle", message: "PostActionText", delegate: self, cancelButtonTitle:"PostActionDecline")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.addButtonWithTitle("PostActionAccept")
alert.show()