How to fetch data from server? [closed] - iphone

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 11 years ago.
I am making an login application in which user can log in.
If the user has already register, then he should be able to log in with the same data saved on server and should be able to get alert view as success and if not the error alert.
Unfortunately, I am not able to do that.
Please help me out.
This is my code:
-(IBAction)btn_login: (id) sender
{
NSString *firstname = Firstname.text;
NSString *lastname = Lastname.text;
NSString *post = [NSString stringWithFormat:#"fname=%#&lname=%#",firstname,lastname];
NSString *hostStr =#"http://www.yoursite.com/iphone.php";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:hostStr]];
NSString *serverOutput = [[NSString alloc]initWithData:dataURL encoding:NSASCIIStringEncoding];
if ([serverOutput isEqualToString:#"Yes"])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Congrats" message:#"You are authorised" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Invalid Username and password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
[alert release];
}
Firstname.text=nil;
Lastname.text=nil;
}
thanks

You need to supply a "?" after the address when appending parameters.
Change
NSString *hostStr=#"http://www.yoursite.com/iphone.php";
to
NSString *hostStr=#"http://www.yoursite.com/iphone.php?";
PS: NSData dataWithContentsOfUrl is a horrible way to do this. Use NSURLConnection and use authentication challenge for Basic Authentication. Read URL Loading System Programming Guide.

Related

iPhone to retrieve gmail account details in app from setting

I am making an application where I want to send an email using smtp server.
It's working fine but if user does not provide the correct gmail account details such as (email id and password) email is not send.
What I want to do is I want to access user gmail account details from setting tab of the iPhone into my app?
Is it possible to do retrieve the gmail account detail into the app?
Please help me out with this.
Following is my code:
-(IBAction)sendemail
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
//testMsg.fromEmail = #"Lexi mobile";//nimit51parekh#gmail.com
testMsg.fromEmail = soundOn;
NSLog(#"str_Uname=%#",testMsg.fromEmail);
//str_info = [str_info stringByReplacingOccurrencesOfString:#"," withString:#""];
testMsg.toEmail = [string_emailinfo objectAtIndex:0];
NSLog(#"autoemail=%#",testMsg.toEmail);
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = soundOn;
NSLog(#"autoelogin=%#",testMsg.login);
testMsg.pass = vibrateOn;
NSLog(#"autopass=%#",testMsg.pass);
testMsg.subject = #"Photo Sharing";
testMsg.wantsSecure = YES;
NSURL *url = [[NSURL alloc]initWithString:#"http://itunes.apple.com/us/app/umix-radio/id467041430?mt=8"];
NSString *msg2 = [NSString stringWithFormat:#"<html><b>DOWNLOAD NOW</b>&nbsp&nbsp</html>",url];
NSString *sendmsg=[[NSString alloc]initWithFormat:#"%#",msg2];
NSLog(#"automsg=%#",sendmsg);
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
sendmsg,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
// [self DeleteRowAfterSending];
//[self performSelector:#selector(DeleteRowAfterSending) withObject:nil afterDelay:5.0];
}
-(void)messageSent:(SKPSMTPMessage *)message
{
[message release];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Your email is sent successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Fail" message:#"Message sending failure" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
What i want to do is i want to access user gamil account details from
setting tab of the iPhone into my app? is it possible to do retrive
the gamil account detail into the app?
No, and with good reason: that functionality would allow any developer access to anyone's e-mail account.
That would be a massive security hole.
Much like it is with Location Services, you're just going to have to ask the user to enter their e-mail address and password. And hope they want to trust your app with that kind of personal information. (Assuming Apple approves your app at all.)
Let the user give your app authorization from Google. check the oauth autorization with google api at their developers site?
https://developers.google.com/accounts/docs/OAuth2
As usual the user signs in with his account through google api and returns back to you an access_token to get information back from his account including his email which you need.

Can't figure out an error with stringWithFormat

I'm having a really basic problem with NSString stringWithFormat. I want to take the name that the user enters and display in an alertView: Welcome username.
NSString *welcomeMessage = [NSString stringWithFormat:(#"Welcome %#", passedData)];
UIAlertView *alert = [[UIAlertView alloc] //show alert box with option to play or exit
initWithTitle: welcomeMessage
message:#"Once you press \"Play\" the timer will start. Good luck!"
delegate:self
cancelButtonTitle:#"I want out!"
otherButtonTitles:#"Play",nil];
[alert show];
passedData is the username that has been entered. The way I have it at the moment - only the username is being displayed in the title of the alert box, and not the "Welcome" part. I know i'm missing some really basic knowledge here but would appreciate some help.
I think that () are not needed. Try using that:
NSString *welcomeMessage = [NSString stringWithFormat:#"Welcome %#", passedData];
instead of
NSString *welcomeMessage = [NSString stringWithFormat:(#"Welcome %#", passedData)];
Hope it helps

How to send an email to a receipent in background in iOS5?

In an iPhone app,I want to send an email to a person who has forgotten about their passcode . I want to send the mail in background (cant use MFMailComposeViewController for this) and also the app must not be pushed to background . Is there a way to achieve this?
The best way of doing this is using SKPSMTPMessage. You can download it from here: https://github.com/jetseven/skpsmtpmessage This is a very easy solution that I have used before for using "Forgot Password" solutions in iOS apps. To implement simply drag the downloaded files into your application, #import the the "SKPSMTPMessage.h" into your class, and implement the following code:
.h
#import "SKPSMTPMessage.h"
#interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
.m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:#"some-email#gmail.com"]; // Change to your email address
[forgotPassword setToEmail:#"user-email#gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:#"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:#"some-email#gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:#"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:#"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required
NSString *newpassword = #"helloworld";
NSString *message = [NSString stringWithFormat:#"Your password has been successfully reset. Your new password: %#", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, #"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}
Also be sure to include the following methods in the .m. You can change the contents of the UIAlertViews depending on what you want to display to the user.
- (void)messageSent:(SKPSMTPMessage *)message {
NSLog(#"Message Sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Password Reset" message:#"Check your email for your new password." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
NSLog(#"Message Failed With Error(s): %#", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
You also need to do the following before this will work.
Your Target -> Get Info -> Build -> All Configurations -> Other Link Flags: "-ObjC"
If you need help with this, see http://developer.apple.com/qa/qa2006/qa1490.html
EDIT:
* CFNetwork.framework must also be added for this to work! *
Let me know if you have any more questions.
Thanks,
Jacob
You can't use MFMailComposeViewController to do this. No API will allow you to send emails or any kind of message on behalf of the user without he seeing it.
The only I see is to make a call to your server and the server send the email, something like this:
NSURLRequest requestWithURL:[NSURL urlWithString:#"http://server.com/send_passcode?to=email#lala.com"]];
You cannot send SMS/Email without user acceptance. But there are a lot of web-services in internet which can send SMS/Email. I guess some app uses those services or uses own.
You CAN send email in the background (without using the default MFMail Controller). BUT you still need the user to fill out whatever form (or content you want to email) and have them click "Send".
Here is my post on how to do it. It includes code and images.
Locking the Fields in MFMailComposeViewController
P.S. this works and Apple has approved over 10 of my apps that use this code/method.
In reference to the PostageApp comment below if you wanted to send emails without any hassle of setting up an SMTP client you can check out the PostageKit wrapper for using the PostageApp service. Let's you send emails with a couple lines of code reliably.
https://github.com/twg/PostageKit
May be you should implement PHP script that will send out email to user. In ios, you can use POST method in NSURLConnection to call PHP script. You can find many scripts on Google to send out email to user.
Download SKPSMTP Library and import
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"
-(IBAction)btnRecoverClicked:(id)Sender;
Then implement the method for sending mail in background.
-(IBAction) btnRecoverClicked:(id)sender {
NSString *str=#"Your password is:";
NSString *strUserPassword=[NSString stringWithFormat:#"%# %#",str,struserPassword];
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"XXXXX"; //sender email address
emailMessage.toEmail = struserEmail; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"xxxxxxxx"; //sender email address
emailMessage.pass = #"XXXXXXX"; //sender email password
emailMessage.subject =#"Password Recovery";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = [NSString stringWithFormat:#"Your password is: %#",struserPassword]
;
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary
dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-
unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
To handle the success and fail use
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
and
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
https://github.com/troyz/MailUtil
I have used library above to send mail in background, so it works.
pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'
Swift code is here:
import MailUtil
SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo#mailserver.com", withLogin: "foo#mailserver.com", withPassword: "*********")
let operation = SendEmailOperation(to: "foo#mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")
operation?.completionBlock = {
debugPrint("Mail sent!")
DispatchQueue.main.async {
//showMailSentPopup()
}
}
do {
try SendEmailOperation.sendEmail(operation)
} catch {
debugPrint("Mail could not sent or sending result could not handle - \(error)")
}

Getting Facebook ID number with API

I know - I have read the documentation - but frankly Facebook is horrible at it. I can't figure out how to send a request that illicits a response. Here's what I'm trying:
NSURL *fbID = [NSURL URLWithString:#"https://graph.facebook.com/me?fields=id"];
fbUserID = [[NSData alloc] initWithContentsOfURL: fbID];
Where should this code go? Is there a specific class it is looking for if I have set 'self' as delegate?
How are you trying to integrate FB into your app? I have been looking into Facebook connect recently and found their documentation very helpful (http://developers.facebook.com/docs/guides/mobile/#ios). I know you said you looked at the documentation, but for me after going through their steps for iOS I was able to make an app that allowed users to sign in and give me access to their basic information, including ID. After going through authorization, I had the following code in my app delegate:
- (void) fbDidLogin {
//get information about the currently logged in user
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSString *name = [result objectForKey:#"name"];
NSString *msg = [[NSString alloc] initWithFormat:#"To prove this works, your name is %#",name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Thanks for Logging In!"
message:msg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
This gets the user's full name after logging in and displays it. You can do the same thing for getting their ID.

iPhone: Using Alerts to Help Debugging

I've been building a rather complex system and there's come the time now where I want more concise debugging. I would like to display the contents of a variable (for this example an NSString called v_string) in a notification window (the kind of window that appear when you receive an SMS text).
Is there an easy way to just call an alert with a variable?
Thanks in Advance,
Dan
NSLog does not do? If not (like if you need to debug an application running on a disconnected device), you can extend the UIAlertView with a category:
#implementation UIAlertView (Logging)
+ (void) log: (id <NSObject>) anObject
{
NSString *message = [anObject description];
UIAlertView *alert = [[self alloc] initWith…];
[alert show];
[alert release];
}
And then in code:
NSString *anInterestingString = …;
[UIAlertView log:anInterestingString];
When you build the string to display in the alert window, simply append your variable's string represenation using stringByAppendingString.
Alert window is cumbersome. Use NSLog instead:
NSLog(#"Variable is: %#", v_string);
And in Xcode's console you will see that text.
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"My Debug String" message:v_string delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[message show];
[message release];
I think this way you can see what you want.
But, as zoul said, why not to use NSLog(#"my var: %#", v_string); ?
Hope that it helps.