How to call NSString from json to UIAlertView? - ios

I would like to pass some values from json to a message of UIAlertView. I have some codes
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
}
- (void)locationView
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Recommendation"
message:[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#."]
delegate: self
cancelButtonTitle: nil
otherButtonTitles: #"GO", nil];
[alert show];
}
As I know, I have to do something in
message:[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#."]. However, I have no idea how to do it. Can someone tell me how to pass the values of lData and rData to the message of uialertview??

You can make a global NSString variable which defines you message
In .h file
NSString *message;
In jsonParse method
- (void)jsonParse {
//Your Stuff
message = [NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#", lData, rData];
}
and then in your UIAlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Recommendation"
message:message
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"GO", nil];
[alert show];

- (void)jsonParse{
//your code
[self locationViewWithRoom:rData level:lData];
}
- (void)locationViewWithRoom:(NSString *)room level:(NSString *)level
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Recommendation"
message:[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#.", room, level]
delegate: self
cancelButtonTitle: nil
otherButtonTitles: #"GO", nil];
[alert show];
}

UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Recommendation"
message:[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#.", iData, rData]
delegate: self
cancelButtonTitle: nil
otherButtonTitles: #"GO", nil];
Just write the values after you write the argument for stringWithFormat. The number of your arguments should match with the number of %#s used in argument string, and your arguments should be comma separated, otherwise you will get a build error.

Declare both the variables (rData & lData) globally (means, in your interface) and then use it like this
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Recommendation"
message:[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#.",lData,rData]
delegate: self
cancelButtonTitle: nil
otherButtonTitles: #"GO", nil];

Its actually pretty easy. You are doing right just few things are missing.
Declare rData & lData as properties in your class,
#interface <classname>
#propert (nonatomic,strong) NSString *lData;
#propert (nonatomic,strong) NSString *rData;
#end
Then your string can be formed using,
[NSString stringWithFormat:#"OK! There is another collection which located at room %# in level %#.", lData, rData];
This should resolve your issue.

Related

xcode display data from json web service

I am using a web service used to display details about person and profile but I don't know how to display the data from web service to labels. I have worked with login validation using web service the code is as below
-(IBAction)login:(id)sender
{
NSString *username=userName.text;
NSString *password=passWord.text;
if ([username length]!=0&&[password length]!=0)
{
NSString *link=[NSStringstringWithFormat:#"http://www.abcd.com/XXX/YYY/Login.ashx/?Username=%#&Password=%#",username,password];
NSURL *URLGet= [NSURL URLWithString:link];
NSData* data = [NSData dataWithContentsOfURL:URLGet];
NSError* error;
XYZ Return array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if ([jasonReturnArray isEqual: #"UserId 4"])
{
Connections *view2=[[Connections alloc]initWithNibName:nil bundle:nil];
view2.modalTransitionStyle= UIModalTransitionStyleFlipHorizontal;
[self presentViewController:view2 animated:NO completion:nil];
NSLog(#"%#",jasonReturnArray);
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok"otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"
message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
It works fine but my doubt is
how to display the data from json web service to my designed labels
Create IBOutlet of your UILabel then set text value of your label as following
for (NSString * singleStringObject in jasonReturnArray)
{
yourLabel.text=[yourLabel.text stringByAppendingString:singleStringObject];
}
in case of single string you just set text of yourLabel without any loop.

how to use Gmail smtp in iOS app

I am new to Xcode I need an app to send a email. Background: the destination email Id is typed in a text and by clicking the send button the message body Sample should go to the destination Email ID I tried this code in the function button clicked but it is not working when ever i try this code I get error in function can any one guide me with a step by step tutorial
mailTransfer[673:207] delegate - error(-5): timeout sending message
2014-07-05 10:54:05.393 mailTransfer[673:207] * stopping watchdog * I had added the SMTP files from google documents ... any other way to correct this code
- (IBAction)sendMessageInBack:(id)anObject
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Yours mail ids";
testMsg.toEmail = emailField.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Your mail ids";
testMsg.pass = #"id password";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,#"Sample",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
in SKPSMTPMessage.m
update the following line
CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
with
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Download SMTP framework and import SKPSMTPMessage class..
#import "SKPSMTPMessage.h"
-(void)sendEmailVideo:(NSString*)_toEmailAddress andCC:(NSString*)ccEmail
{
#try
{
// Message =[data getContentOfPanic];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail=#"nikki.varsha#gmail.com";//sender email address
emailMessage.toEmail=_toEmailAddress;
//receiver email address
emailMessage.relayHost=#"smtp.gmail.com";
//emailMessage.ccEmail =ccEmail;
emailMessage.requiresAuth = YES;
emailMessage.login = #"nikki.varsha#gmail.com"; //sender email address
emailMessage.pass = #"123";
//sender email password
emailMessage.subject =#"Panic Video Message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
Message,kSKPSMTPPartMessageKey,#"8bit", kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"Video.mov\"",kSKPSMTPPartContentTypeKey,
#"attachment;\r\n\tfilename=\"Video.mov\"",kSKPSMTPPartContentDispositionKey,[webData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts=[NSArray arrayWithObjects:plainPart,vcfPart,nil];
dispatch_queue_t backgroundVideoQueue = dispatch_queue_create("com.VideoQue", 0);
dispatch_sync(backgroundVideoQueue, ^{
[emailMessage send];
});
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Host" message:#"No Reciever Email Ids Available! " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
pragma mark - sendEmail delegate (SKPSMTPMessage)
-(void)messageSent:(SKPSMTPMessage *)message
{
NSLog(#"delegate - Email sent");
NSLog(#"Mesg %#",message);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"err=%#" ,message);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Unable to send email Please Check EmailId & Password"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
});
}
in SKPSMTPMessage.m file do change the following line
Remove this line
//CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
Add this line
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Thanks

Passing NSString into UIAlertview's message content

I would like to display something like this: SampleUser poked you. in a UIAlertView's message, but actually i'm getting errors. I know how to do it with a simple string, i don't know how to do it with a string that contains another string.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Poke" message:#"%# poked you.", self.senderString delegate:self cancelButtonTitle:#"Yes" otherButtonTitles:#"No", nil];
[alertView show];
You should create your composed-NSString first and then call it in your UIAlertView:
NSString *message = [NSString stringWithFormat:#"%# poked you.", userName];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Poke" message:message, self.senderString delegate:self cancelButtonTitle:#"Yes" otherButtonTitles:#"No", nil];
[alertView show];
The problem here is that for the message: argument, you're attempting to send this:
#"%# poked you.", userName
This doesn't make any sense.
Instead, you need to send an NSString object as the argument.
NSString *message = [NSString stringWithFormat:#"%# poked you.", self.senderString];
Now that we've created an NSString object, we can use this object as the message argument.
You could create this object embedded in the call to create the alert view, but for readability and debugging , it's better to do it this way.
NSString *message = [NSString stringWithFormat:#"%# poked you.", self.senderString];
UIAlertView *pokeAlert = [[UIAlertView alloc] initWithTitle:#"Poke"
message:message
delegate:self
cancelButtonTitle:#"Yes"
otherButtonTitles:#"No", nil];
[pokeAlert show];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Poke" message:[NSString stringWithFormat:#"%# poked you.", self.senderString] delegate:self cancelButtonTitle:#"Yes" otherButtonTitles:#"No", nil];
[alertView show];

Property 'tag' not found on object of type '_strong id'

I am building an App according to this tutorial (http://bit.ly/NI9kQe) which uses a custom web api to connect to the web server. One of the requirements is to detect whether or not the Login or Register button has been tapped. This is done using a "tag" which has been set for the button in interface builder (the register button has a tag of 1).
The chunk of code sits inside the btnLoginRegisterTapped method as follows (the error occurs on the line -> NSString* command = (sender.tag==1)?#"register":#"login";):
- (IBAction)btnLoginRegisterTapped:(id)sender {
//form fields validation
if (fldUserName.text.length < 4 || fldPassword.text.length < 4) {
// [UIAlertView error:#"Enter username and password over 4 chars each."];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Enter username and password over 4 chars each." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
return;
}
//salt the password
NSString* saltedPassword = [NSString stringWithFormat:#"%#%#", fldPassword.text, kSalt];
//prepare the hashed storage
NSString* hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
//hash the pass
NSData *data = [saltedPassword dataUsingEncoding: NSUTF8StringEncoding];
if (CC_SHA1([data bytes], [data length], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Password cannot be reset!" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
return;
}
//************ THIS IS WHERE THE ERROR OCCURS *****************//
//check whether it's a login or register
NSString* command = (sender.tag==1)?#"register":#"login";
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
command, #"command",
fldUserName.text, #"username",
hashedPassword, #"password",
nil];
//make the call to the web API
[[API sharedInstance] commandWithParams:params
onCompletion:^(NSDictionary *json) {
//handle the response
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
//success
[[API sharedInstance] setUser: res];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//show message to the user
[[[UIAlertView alloc] initWithTitle:#"Logged in"
message:[NSString stringWithFormat:#"Welcome %#",[res objectForKey:#"username"] ]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles: nil] show];
} else {
//error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Opps!!" message:#"Server down? Try Again" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
// optional - add more buttons:
[alert addButtonWithTitle:#"Yes"];
[alert show];
return;
}
}];
}
when I try to build the project (workspace actually) I get the error:
Property 'tag' not found on object of type '_strong id'
I am using xcode 5.0 deploying for iOS7.
Thanks,
Property syntax cannot be used with variables of the generic id type.
So either replace sender.tag by the method call [sender tag] or better,
use the actual type of the sender argument in the method definition:
- (IBAction)btnLoginRegisterTapped:(UIButton *)sender { ... }
Tip: When creating the action with "Control-Drag" in Xcode,
use the pop-up in the "Type" field to select the actual type of the sender.
Then the action method is created with the correct argument type.

Writetourl does not work

I have tried for a week to get writeToUrl to work, but no... nothing.
I simply want to update a file on my server from an iPhone app.
This is the code:
NSURL *url = [NSURL URLWithString:#"http://user:pw#192.168.120.167/test.txt"];
NSString *teststring = #"it works";
if ([teststring writeToURL:url atomically:YES encoding:NSASCIIStringEncoding error:nil]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Status" message: #"Yessss" delegate: self cancelButtonTitle: #"Close" otherButtonTitles: nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Status" message: #"Noooooo" delegate: self cancelButtonTitle: #"Close" otherButtonTitles: nil];
[alert show];
[alert release];
}
I switched from writeToURL to writeToFile, using the exact same file path, and it suddenly worked. Seems like there might be a bug in writeToURL. This was tested on iOS 7.1.
You can only write to local files. See documentation:
Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:options:error:, except for the type of the first argument.

Resources