I am developing on app in that i want to send email at the back ground.
for that i used the "SKPSMTP" library but when i got the mail it is without body so can any one tell me where i m wrong in my code.
following is the code on button click..
- (void)sendMessageInBack:(id)anObject
{
if(![self validateEmail:txt_email.text])
{
if([txt_email.text isEqualToString:#""] )
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Mandatory field" message:#"Please fill complete email" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
if(self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation==UIInterfaceOrientationLandscapeRight )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send_button.png"] forState:UIControlStateNormal];
}
else if(self.interfaceOrientation==UIInterfaceOrientationPortrait || self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send button1.png"] forState:UIControlStateNormal];
}
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"RequestReview.txt"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
//NSString *mailid;
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail =#"spymekdemo#gmail.com";
testMsg.toEmail = #"priyanka.chinchmalatpure#gmail.com";// txtEmail.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"spymekdemo#gmail.com";
testMsg.pass =#"spymek123";
testMsg.subject =#"Sbject"; //[NSString stringWithFormat:#"Reply to Review From %#", txtName.text];
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSString *deviceIdentifier=[NSString stringWithFormat:#"%#",[[UIDevice currentDevice]uniqueIdentifier]];//[NSString stringWithFormat:#"%#",deviceToken.uniqueIdentifier];
NSLog(#"%#",deviceIdentifier);
//NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
// [NSString stringWithFormat:#"Request Review\n\nDevice Identifier=%#\nProduct Name=%#\nProduct Download URL=%#\nUser Name=%#\nEmail=%#\nPromo Code=%#\nDescription Of Product=%#\n\n\n", deviceIdentifier, txtProduct.text,txtDownloadURL.text, txtName.text,txtEmail.text,txtPromocode.text, txtDescription.text]
// ,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"<h2>Request Review</h2><br/><br/><b>Thank you for giving us your review</b> <br/>Device Identifier=%#<br/>Product Name=<br/>Product Download URL=<br/>User Name=<br/>Email=<br/>Promo Code=<br/>Description Of Product=<br/><br/><br/>", deviceIdentifier]
,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// [NSString stringWithFormat:#"<h3>Review App</h3> <br/> <br/><b>Name=%#<b><br/> <br/>,\n<u>Email=%#</u><br/> <br/>,\nPassword=%#,<br/><br/> <b>\nComments=%#\n\n</b><br/>",txtName.text,txtMailId.text, txtPassword.text, txtComment.text],kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// #"<html><body><h1>Review App</h1> <br/> <b>Some text to include in body</b></body></html>"
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"attachment;\r\n\tfilename=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentDispositionKey,[dataObj encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,vcfPart, nil]; //vcfPart
[testMsg send];
}
}
rotate=YES;
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
//open an alert with just an OK button
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]);
//[self ClearFile];
//UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Request Review" message:#"Review Posting failed.. Try Again Later.." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
}
- (void)messageSent:(SKPSMTPMessage *)message
{
[message release];
NSLog(#"delegate - message sent");
}
Related
the below code successfuly post my text on facebook wall now i want to post a image along with text using Below code
- (IBAction)callFacebookAPI:(id)sender
{
[self.txtinputfield resignFirstResponder];
if (txtinputfield.text.length !=0)
{
//create the instance of graph api
objFBGraph = [[FbGraph alloc]initWithFbClientID:FbClientID];
//mark some permissions for your access token so that it knows what permissions it has
[objFBGraph authenticateUserWithCallbackObject:self andSelector:#selector(FBGraphResponse) andExtendedPermissions:#"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins,publish_checkins,email"];
}
else
{
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"Kindly enter data in the text field" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
- (void)FBGraphResponse
{
#try
{
if (objFBGraph.accessToken)
{
SBJSON *jsonparser = [[SBJSON alloc]init];
FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:#"me" withGetVars:nil];
NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];
NSDictionary *dict = [jsonparser objectWithString:resultString];
NSLog(#"Dict = %#",dict);
NSMutableDictionary *variable = [[NSMutableDictionary alloc]initWithCapacity:1];
[variable setObject:txtinputfield.text forKey:#"message"];
[objFBGraph doGraphPost:#"me/feed" withPostVars:variable];
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"String posted on your wall and you may check the console now" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
#catch (NSException *exception) {
UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:#"Alert" message:[NSString stringWithFormat:#"Something bad happened due to %#",[exception reason]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objALert show];
}
txtinputfield.text = clearText;
}
I tried some methods but did'nt work for me, i have no experience with Graph Api Any help will be appriated.Thanks
Try like below:
- (IBAction)buttonClicked:(id)sender
{
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
}
- (void)fbDidLogin
{
NSString *filePath =pathToImage;
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, pathToImage,
#"picture/jpeg", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
-(void)fbDidNotLogin:(BOOL)cancelled
{
NSLog(#"did not login");
}
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
NSLog(#"Result of API call: %#", result);
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"Failed with error: %#", [error localizedDescription]);
}
I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}
I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/
MGTwitterEngine.m
- (NSString *)username
{
return [[_username retain] autorelease];
}
- (NSString *)password
{
return [[_password retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
[_password release];
_password = [newPassword retain];
if ([self clearsCookies]) {
// Remove all cookies for twitter, to ensure next connection uses new credentials.
NSString *urlString = [NSString stringWithFormat:#"%#://%#",
(_secureConnection) ? #"https" : #"http",
_APIDomain];
NSURL *url = [NSURL URLWithString:urlString];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSEnumerator *enumerator = [[cookieStorage cookiesForURL:url] objectEnumerator];
NSHTTPCookie *cookie = nil;
while (cookie == [enumerator nextObject]) {
[cookieStorage deleteCookie:cookie];
}
}
}
- (NSString *)sendUpdate:(NSString *)status
{
return [self sendUpdate:status inReplyTo:0];
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
TwitterPostViewController.m
- (IBAction)submitTweet{
[tweet resignFirstResponder];
if([[tweet text] length] > 0){
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterUsername"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterPassword"]);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[engine sendUpdate:[tweet text]];
}
}
- (void)requestFailed:(NSString *)requestIdentifier withError:(NSError *)error{
NSLog(#"Fail: %#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *failAlert;
if([error code] == 401){
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Incorrect Username & Password." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[failAlert setTag:10];
[failAlert setDelegate:self];
}
else
{
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed sending status to Twitter." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
[failAlert show];
[failAlert release];
}
It shows me the fail popup of Incorrect username and password
I have checked through nslog that username and password are going correct.
what could be wrong?
It looks like the version of MGTwitterEngine you're using is trying to use basic auth. That was switched off in Twitter in favour of OAuth. Get a newer version of MGTwitterEngine (or a fork that supports OAuth).
I am creating an iphone application in which I have to upload photos using different services.
I am successful in uploading photos with Twitpic & YFrog but not able to do with Plixi.
I am using Oauth ,as Twitter is not allowing Basic authentication.
If anyone has tried with Plixi ,please help me out!!
I have googled a lot but not getting any relevant documentation for the new Oauth for Plixi.
Finally, I am with a solution for my problem :)
If anyone is also stuck with this problem, just add the TweetPhoto folder from the following application link:
http://code.google.com/p/tweetphoto-api-objective-c/downloads/detail?name=TPAPI-Objective-C-Library.zip
Change the tweetphoto urls for plixi now.
Also, can refer to my following code for making function calls:
-(void)uploadtoTweetPhoto{
NSString *message = [self.tweetTextView.text stringByReplacingOccurrencesOfString:#"Max. 140 characters" withString:#""];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
if((message == nil) || ([message isEqual:#""])){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Please enter your tweet message.." message: #"" delegate:nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
else{
[dictionary setObject:message forKey:#"message"];
}
if([dictionary count] == 1){
[indicator startAnimating];
[NSThread detachNewThreadSelector:#selector(uploadPhotoToTweetPhoto:) toTarget:self withObject:dictionary];
}
[dictionary release];
}
- (void)uploadPhotoToTweetPhoto:(NSDictionary *)dictionary{
NSString *message = [dictionary objectForKey:#"message"];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *accessTokenKey = [[NSUserDefaults standardUserDefaults] valueForKey:#"oauth_token"];
NSString *accessTokenSecret = [[NSUserDefaults standardUserDefaults] valueForKey:#"oauth_token_secret"];
TweetPhoto *tweetPhoto = [[TweetPhoto alloc] initWithSetup:accessTokenKey identitySecret:accessTokenSecret apiKey:Plixi_API_Key serviceName:#"Twitter" isoAuth:YES];
NSData *dat =[tweetPhoto upload:UIImageJPEGRepresentation(self.imgView.image,0.8) comment:message tags:#"" latitude:23.4646 longitude:-87.7809 returnType:TweetPhotoCommentReturnTypeXML];
NSString *status =[NSString stringWithFormat:#"%i",[tweetPhoto statusCode]];
[tweetPhoto release];
[self performSelectorOnMainThread:#selector(photoUploadedtoTweetPhoto:) withObject:status waitUntilDone:[NSThread isMainThread]];
[pool release];
}
- (void)photoUploadedtoTweetPhoto:(NSString*)status{
[indicator stopAnimating];
if([status isEqualToString:#"201"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Tweet Posted" message: #"" delegate:nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Tweet Failed" message: #"" delegate:nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
I'm curious as to the phrase you used in Google. In any case, googling "plixi api" tool me to this page, which links to a Cocoa wrapper on Google Code.