problem submitting tweet to twitter from iphone - iphone

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).

Related

how to check in iphone app if url is valid then load in WebVIew else show alert

I have app in which i want that when user enter url in textfield and presses return key it should check if url is valid then load url in web view else show alert enter valid url
In my code it always show Valid URL.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
[self urlIsValiad:test];
if ([test isEqualToString:#"Valid"]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}
- (BOOL) urlIsValiad: (NSString *) url
{
NSString *regex =
#"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this
///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,#?^=%&:/~+#]* [\w-\#?^=%&/~+#])?";
NSPredicate *regextest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if ([regextest evaluateWithObject: url] == YES) {
NSLog(#"URL is valid!");
test=#"Valid";
} else {
NSLog(#"URL is not valid!");
test=#"Not Valid";
}
return [regextest evaluateWithObject:url];
}
// .h File
-(BOOL)validateUrl;
.m File
-(BOOL)validateUrl{
NSString *urlRegEx = #"((?:http|https)://)?(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
if ([urlTest evaluateWithObject: self] == YES) {
NSLog(#"URL is valid!");
} else {
NSLog(#"URL is not valid!");
}
return [urlTest evaluateWithObject:self];
}
// Main View Controller .m File
if (![txtWebsite.text validateUrl])
{
[KWebsiteURLTypeValidation showAsAlert:self];
return;
}
You can use this method:
- (BOOL) validateUrl: (NSString *) url {
NSString *theURL =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", theURL];
return [urlTest evaluateWithObject:url];
}
From Check URL validity . Hope this helps.
i've modified your code so please replace this method with your code and it will work superfine
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
if ([self urlIsValiad:test]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}

Advertisements not removed after IAP unless app is restarted?

In my app, there is code that, if a button is pressed the user can upgrade the app and remove the advertisements, it calls the MKStoreKit and once the user purchases the upgrade, the adverts do remain in the app UNTIL the app is restarted.
I want to fix this, so the advertisements are removed immediately, but how would I go about doing this?
Here is some of the code;
-(IBAction)removeAds:(id)sender
{
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Upgrade App" message:#"To upgrade and remove all advertisements from this app Please click OK to purchase the upgrade!" delegate:self cancelButtonTitle:#"No Thanks" otherButtonTitles:#"Yes Please",nil];
[alert show];
[alert release];
}
}
The alert it links to;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#"com.idevver.mybatterypal.upgrade"];
}
}
}
Using MKStoreKit
Is there anything I can do to make it remove the advertisements without the user having to restart the app?
Thanks,
Chris
EDIT - the advertisements are Admob Mediation, using this code in the ViewDidLoad
- (void)viewDidLoad {
bannerView_ = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat screenXPos = (screenWidth /2);
CGFloat screenYPos = screenHeight - 90;
[bannerView_ setCenter:CGPointMake(screenXPos, screenYPos)];
bannerView_.rootViewController = self;
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];
This is the code that actually calls the advertisement banner, it is in an if/else statement later in the viewDidLoad
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
[bannerView_ loadRequest:[GADRequest request]];
}
So I guess somehow when the feature is purchased, I need to add to the MKStoreManager.m file something to say dismiss the bannerView_ code above?
Would that work?
EDIT 2 - Full .m file for the in-app code (with thanks to MugunthKumar for a wonderful kit)
//
// MKStoreManager.m
// MKStoreKit
//
// Created by Mugunth Kumar on 17-Nov-2010.
// Copyright 2010 Steinlogic. All rights reserved.
// File created using Singleton XCode Template by Mugunth Kumar (http://mugunthkumar.com
// Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
// Read my blog post at http://mk.sg/1m on how to use this code
// As a side note on using this code, you might consider giving some credit to me by
// 1) linking my website from your app's website
// 2) or crediting me inside the app's credits page
// 3) or a tweet mentioning #mugunthkumar
// 4) A paypal donation to mugunth.kumar#gmail.com
//
// A note on redistribution
// While I'm ok with modifications to this source code,
// if you are re-publishing after editing, please retain the above copyright notices
#import "MKStoreManager.h"
#import "GADBannerView.h"
#import "AppDelegate.h"
#interface MKStoreManager (PrivateMethods)
- (void) requestProductData;
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID;
- (BOOL) verifyReceipt:(NSData*) receiptData;
- (void) enableContentForThisSession: (NSString*) productIdentifier;
#end
#implementation MKStoreManager
#synthesize purchasableObjects = _purchasableObjects;
#synthesize storeObserver = _storeObserver;
static NSString *ownServer = nil;
static __weak id<MKStoreKitDelegate> _delegate;
static MKStoreManager* _sharedStoreManager;
- (void)dealloc {
[_purchasableObjects release];
[_storeObserver release];
[_sharedStoreManager release];
[super dealloc];
}
#pragma mark Delegates
+ (id)delegate {
return _delegate;
}
+ (void)setDelegate:(id)newDelegate {
_delegate = newDelegate;
}
#pragma mark Singleton Methods
+ (MKStoreManager*)sharedManager
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
#if TARGET_IPHONE_SIMULATOR
NSLog(#"You are running in Simulator MKStoreKit runs only on devices");
#else
_sharedStoreManager = [[self alloc] init];
_sharedStoreManager.purchasableObjects = [[NSMutableArray alloc] init];
[_sharedStoreManager requestProductData];
_sharedStoreManager.storeObserver = [[MKStoreObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:_sharedStoreManager.storeObserver];
#endif
}
}
return _sharedStoreManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
_sharedStoreManager = [super allocWithZone:zone];
return _sharedStoreManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
#pragma mark Internal MKStoreKit functions
- (void) restorePreviousTransactions
{
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
-(void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:
kFeatureAId,
kConsumableFeatureBId,
kConsumableBaseFeatureId,
nil]];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
[self.purchasableObjects addObjectsFromArray:response.products];
#ifndef NDEBUG
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSLog(#"Feature: %#, Cost: %f, ID: %#",[product localizedTitle],
[[product price] doubleValue], [product productIdentifier]);
}
for(NSString *invalidProduct in response.invalidProductIdentifiers)
NSLog(#"Problem in iTunes connect configuration for product: %#", invalidProduct);
#endif
[request autorelease];
isProductsAvailable = YES;
if([_delegate respondsToSelector:#selector(productFetchComplete)])
[_delegate productFetchComplete];
}
// call this function to check if the user has already purchased your feature
+ (BOOL) isFeaturePurchased:(NSString*) featureId
{
return [[NSUserDefaults standardUserDefaults] boolForKey:featureId];
}
// Call this function to populate your UI
// this function automatically formats the currency based on the user's locale
- (NSMutableArray*) purchasableObjectsDescription
{
NSMutableArray *productDescriptions = [[NSMutableArray alloc] initWithCapacity:[self.purchasableObjects count]];
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
[numberFormatter release];
// you might probably need to change this line to suit your UI needs
NSString *description = [NSString stringWithFormat:#"%# (%#)",[product localizedTitle], formattedString];
#ifndef NDEBUG
NSLog(#"Product %d - %#", i, description);
#endif
[productDescriptions addObject: description];
}
[productDescriptions autorelease];
return productDescriptions;
}
- (void) buyFeature:(NSString*) featureId
{
if([self canCurrentDeviceUseFeature: featureId])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Review request approved", #"")
message:NSLocalizedString(#"You can use this feature for reviewing the app.", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles:nil];
[alert show];
[alert release];
[self enableContentForThisSession:featureId];
return;
}
if ([SKPaymentQueue canMakePayments])
{
SKPayment *payment = [SKPayment paymentWithProductIdentifier:featureId];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"In-App Purchasing disabled", #"")
message:NSLocalizedString(#"Check your parental control settings and try again later", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count > 0);
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count >= quantity);
}
- (BOOL) consumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
if(count < quantity)
{
return NO;
}
else
{
count -= quantity;
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:productIdentifier];
return YES;
}
}
-(void) enableContentForThisSession: (NSString*) productIdentifier
{
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
}
#pragma mark In-App purchases callbacks
// In most cases you don't have to touch these methods
-(void) provideContent: (NSString*) productIdentifier
forReceipt:(NSData*) receiptData
{
if(ownServer != nil && SERVER_PRODUCT_MODEL)
{
// ping server and get response before serializing the product
// this is a blocking call to post receipt data to your server
// it should normally take a couple of seconds on a good 3G connection
if(![self verifyReceipt:receiptData]) return;
}
NSRange range = [productIdentifier rangeOfString:kConsumableBaseFeatureId];
NSString *countText = [productIdentifier substringFromIndex:range.location+[kConsumableBaseFeatureId length]];
int quantityPurchased = [countText intValue];
if(quantityPurchased != 0)
{
int oldCount = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
oldCount += quantityPurchased;
[[NSUserDefaults standardUserDefaults] setInteger:oldCount forKey:productIdentifier];
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
}
[[NSUserDefaults standardUserDefaults] synchronize];
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"In-App Upgrade" message:#"Successfull removal of advertisements upgrade - thankyou" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
- (void) transactionCanceled: (SKPaymentTransaction *)transaction
{
#ifndef NDEBUG
NSLog(#"User cancelled transaction: %#", [transaction description]);
#endif
if([_delegate respondsToSelector:#selector(transactionCanceled)])
[_delegate transactionCanceled];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[transaction.error localizedFailureReason]
message:[transaction.error localizedRecoverySuggestion]
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
#pragma mark In-App purchases promo codes support
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/31
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID
{
NSString *uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
// check udid and featureid with developer's server
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"featureCheck.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *postData = [NSString stringWithFormat:#"productid=%#&udid=%#", featureID, uniqueID];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/
-(BOOL) verifyReceipt:(NSData*) receiptData
{
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"verifyProduct.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *receiptDataString = [[NSString alloc] initWithData:receiptData encoding:NSASCIIStringEncoding];
NSString *postData = [NSString stringWithFormat:#"receiptdata=%#", receiptDataString];
[receiptDataString release];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
#end
When the purchase completes, it is up to you to remove the ads. Do something similar to this.
[bannerView removeFromSuperview];
All you have to do is hide the ads when the purchase completes.

How to get cookies and use them for other requests like POST ( iOS )?

My previous question was about the problem that I have to login each time for doing web services like posting a link or uploading a picture. Philipe answered that I have to use cookies instead of login process for each request. I found this method for getting cookies:
- (void)getCookies {
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest *request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://MyWebsite.com/login.php"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:120];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://MyWebsite.com/login.php"]];
NSLog(#"%d", all.count);
for (NSHTTPCookie *cookie in all) {
NSLog(#"Name: %# : Value: %#", cookie.name, cookie.value);
NSLog(#"Comment: %# : CommentURL: %#", cookie.comment, cookie.commentURL);
NSLog(#"Domain: %# : ExpiresDate: %#", cookie.domain, cookie.expiresDate);
NSLog(#"isHTTPOnly: %c : isSecure: %c", cookie.isHTTPOnly, cookie.isSecure);
NSLog(#"isSessionOnly: %c : path: %#", cookie.isSessionOnly, cookie.path);
NSLog(#"portList: %# : properties: %#", cookie.portList, cookie.properties);
NSLog(#"version: %u", cookie.version);
}
}
I also found this code to use these cookies, but I'm not sure how to use it:
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookies];
Here is my method for POSTing, I am using RestKit API:
- (IBAction)addLinkPressed:(UIButton *)sender {
[RKClient clientWithBaseURLString:#"http://MyWebsite.com"];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
self.linkField.text, #"url",
self.linkTitleField.text, #"title",
self.linkSummaryField.text, #"summary",
nil];
RKRequest *request = [[RKClient sharedClient] post:#"/send_link.php" params:params delegate:self];
[request setUserData:#"sendLink"];
}
Question: Which property of cookies should I store to use it for login information and where should I put it in my code?
I solved this issue by some inefficient way. Here is my methodology:
First I try to post to the web service and after posting I parse the returning HTML to see if the posting was successful or not. If posting was successful I give an appropriate message to the user that you post successfully but if it was not successful it could have two reasons: First: there were some error during the post execution Second: the user was not logged in. The way that I recognize the differentiation between fist and second error is just parsing the response HTML.
Here is the code that I used for this methodology (this is for the time that the user wants to change the password)
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
NSRange range = [[error localizedDescription] rangeOfString:#"-1012"];
if (range.length > 0){
//First error occurs here
}
RKLogError(#"Hit error: %#", error);
}
- (IBAction)requestToChangePasswordPressed {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
[RKClient clientWithBaseURLString:#"http://WebServiceDomain.com"];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
self.oldPasswordField.text, #"oldPassword",
self.passwordNew.text, #"newPassword",
self.confirmPasswordField.text, #"confirmPassword",
nil];
RKRequest *request = [[RKClient sharedClient] post:#"/change_password.php" params:params delegate:self];
[request setUserData:#"changePassword"];
[self.view endEditing:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)autoLogin {
[RKClient clientWithBaseURLString:#"http://WebServiceDomain.com"];
[RKObjectManager sharedManager].client=[RKClient sharedClient];
RKParams *parameters = [RKParams params];
[parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:#"defaultUsername"] forParam:#"username"];
[parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:#"defaultPassword"] forParam:#"password"];
[[RKClient sharedClient] setAuthenticationType:RKRequestAuthenticationTypeHTTP];
// because we have two POSTs and we want to use the same method for both of the for didLoadResponse: we set the UserDate like bellow
RKRequest *request = [[RKClient sharedClient] post:#"/login.php" params:parameters delegate:self];
[request setUserData:#"login"];
}
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
id userData = [request userData];
if ([userData isEqual:#"login"]) {
if ([request isGET]) {
// Handling GET /foo.xml
if ([response isOK]) {
// Success! Let's take a look at the data
NSLog(#"Retrieved XML: %#", [response bodyAsString]);
}
} else if ([request isPOST]) {
// Handling POST /other.json
if ([response isJSON]) {
NSLog(#"Got a JSON response back from our POST!");
}
} else if ([request isDELETE]) {
// Handling DELETE /missing_resource.txt
if ([response isNotFound]) {
NSLog(#"The resource path '%#' was not found.", [request resourcePath]);
}
}
}
else if ([userData isEqual:#"sendLink"]) {
NSData *addLinksHtmlData = response.body;
// 2
TFHpple *addlinksParser = [TFHpple hppleWithHTMLData:addLinksHtmlData];
// 3
NSString *errorLinksXpathQueryString = #"//div[#class='errorBox']/ul/li";
NSArray *errorLinksNodes = [addlinksParser searchWithXPathQuery:errorLinksXpathQueryString];
// 4
NSMutableArray *newErrorLinks = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in errorLinksNodes) {
// 5
AllModels *errorTitle = [[AllModels alloc] init];
[newErrorLinks addObject:errorTitle];
// 6
errorTitle.errorTitle = [[element firstChild] content];
}
// 8
self.linkErrorObjects = newErrorLinks;
NSString *successLinksXpathQueryString = #"//div[#class='successBox']";
NSArray *successLinksNodes = [addlinksParser searchWithXPathQuery:successLinksXpathQueryString];
// 4
NSMutableArray *newSuccessLinks = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in successLinksNodes) {
// 5
AllModels *successTitle = [[AllModels alloc] init];
[newSuccessLinks addObject:successTitle];
// 6
successTitle.successTitle = [[element firstChild] content];
}
// 8
self.linkSuccessObjects = newSuccessLinks;
}
else {
NSLog(#"HTTP status code: %d", response.statusCode);
NSLog(#"HTTP status message: %#", [response localizedStatusCodeString]);
NSLog(#"Header fields: %#", response.allHeaderFields);
NSLog(#"Body: %#", response.bodyAsString);
NSData *HtmlData = response.body;
// 2
TFHpple *addParser = [TFHpple hppleWithHTMLData:HtmlData];
// 3
NSString *errorXpathQueryString = #"//div[#class='errorBox']/ul/li";
NSArray *errorNodes = [addParser searchWithXPathQuery:errorXpathQueryString];
// 4
NSMutableArray *newError = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in errorNodes) {
// 5
AllModels *errorTitle = [[AllModels alloc] init];
[newError addObject:errorTitle];
// 6
errorTitle.errorTitle = [[element firstChild] content];
}
// 8
self.ErrorObjects = newError;
NSString *successXpathQueryString = #"//div[#class='successBox']";
NSArray *successNodes = [addParser searchWithXPathQuery:successXpathQueryString];
// 4
NSMutableArray *newSuccess = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in successNodes) {
// 5
AllModels *successTitle = [[AllModels alloc] init];
[newSuccess addObject:successTitle];
// 6
successTitle.successTitle = [[element firstChild] content];
}
// 8
self.successObjects = newSuccess;
[self errorCheck];
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)errorCheck {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
if(self.errorObjects.count > 0) {
AllModels *errorlink = [self.errorObjects objectAtIndex:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"There is a problem" message:errorlink.errorTitle delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil , nil];
[alert show];
}
else {
if(self.linkErrorObjects.count > 0) {
[self autoLogin];
[self requestToChangePasswordPressed];
}
else {
AllModels *successlink = [self.successObjects objectAtIndex:0];
self.successLabel.hidden = NO;
self.successLabel.text = successlink.successTitle;
NSLog(#"Success Title: %#",successlink.successTitle);
[UIView animateWithDuration:3.0
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{ self.successLabel.alpha = 0.0; }
completion:^(BOOL fin) { if (fin) [self.successLabel removeFromSuperview]; }];
[self performSelector:#selector(dismissModalViewController) withObject:nil afterDelay:1.0];
}
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}

AVAudioPlayer won't play existing file a second time

I have searched a lot trying to figure this out - the code to me seems ok but the functionality doesn't reflect this.
I have a View that is presented (its an Audio Recorder view). You can press record and it records to a file just fine (data exists in the file). I can then play the file back via the play button (the AVAudioPlayer is pointing to that file).
However when I close/dismiss that view and come back to it - the file will not play when Play is tapped even though it should be exactly the same code as the file location has not changed.
UPDATE:
Seems that [audioPlayer play] returns no. I have also looked into the data. It seems that when the view appears again and loads that data it doesnt load it correctly (NSdata in Nslog displays mainly 0's) - even though the file exists and has data in it (i can see and hear it after transferring to my mac).
This leads me to suspect that either I am loading the data wrong or avaudioplayer wont read the data for some reason...
Please take a look at the code below:
(NSString *) removeCharsFrom: (NSString *) remover {
remover = [remover stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
remover = [remover stringByReplacingOccurrencesOfString:#" " withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"/" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"\\" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#":" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#";" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"(" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#")" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"£" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"$" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"&" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"'" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"{" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"}" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"[" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"]" withString:#"_"];
remover = [remover stringByReplacingOccurrencesOfString:#"""" withString:#"_"];
return remover;
}
- (NSString *) audioPathForResource: (NSString *) audio {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *newFolder = [saveDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#/Audio",catName]];
if (![[NSFileManager defaultManager] fileExistsAtPath:newFolder]) {
[[NSFileManager defaultManager] createDirectoryAtPath:newFolder withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *saveFileName = [NSString stringWithFormat:#"%#.caf",audio];
NSString *newFilePath = [newFolder stringByAppendingPathComponent:saveFileName];
return [newFilePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
- (IBAction)cancelTapped:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)saveTapped:(id)sender {
[self.parentViewController performSelector:#selector(changeAddAudioIcon)];
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)trashTapped:(id)sender {
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: #"Delete"
message: #"Would you like to delete the audio file? Warning: This cannot be undone."
delegate: self
cancelButtonTitle: #"Cancel"
otherButtonTitles: #"Delete", nil];
[alert show];
[alert release];
}
- (IBAction)pauseTapped:(id)sender {
pauseBtn.enabled = NO;
playBtn.enabled = YES;
recordBtn.enabled = YES;
trashBtn.enabled = YES;
if (audioRecorder.recording)
{
[audioRecorder stop];
} else if (audioPlayer.playing) {
[audioPlayer stop];
}
}
- (IBAction)recordTapped:(id)sender {
if (!audioRecorder.recording)
{
playBtn.enabled = NO;
pauseBtn.enabled = YES;
trashBtn.enabled = NO;
[audioRecorder record];
}
}
- (IBAction)playTapped:(id)sender {
pauseBtn.enabled = YES;
recordBtn.enabled = NO;
trashBtn.enabled = YES;
NSError *error;
NSLog(#"%#",filepathstring);
NSURL *soundFileURL = [NSURL fileURLWithPath:filepathstring];
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:soundFileURL
error:&error];
audioPlayer.delegate = self;
if (error)
NSLog(#"Error: %#",
[error localizedDescription]);
else
[audioPlayer play];
}
- (void)alertView: (UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
return;
break;
case 1:
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filepathstring error:&error];
trashBtn.enabled = NO;
}
break;
default:
break;
}
}
-(void)audioPlayerDidFinishPlaying:
(AVAudioPlayer *)player successfully:(BOOL)flag
{
recordBtn.enabled = YES;
pauseBtn.enabled = NO;
playBtn.enabled = YES;
if(player != audioPlayer) {
[player release];
}
}
-(void)audioPlayerDecodeErrorDidOccur:
(AVAudioPlayer *)player
error:(NSError *)error
{
NSLog(#"Decode Error occurred");
}
-(void)audioRecorderDidFinishRecording:
(AVAudioRecorder *)recorder
successfully:(BOOL)flag
{
NSLog(#"Recording success:%#",flag ? #"YES" : #"NO");
trashBtn.enabled = YES;
pauseBtn.enabled = NO;
playBtn.enabled = YES;
}
-(void)audioRecorderEncodeErrorDidOccur:
(AVAudioRecorder *)recorder
error:(NSError *)error
{
NSLog(#"Encode Error occurred");
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void) viewWillAppear:(BOOL)animated {
catName = [NSString stringWithFormat:#"%#",[self removeCharsFrom:catName]];
testName = [NSString stringWithFormat:#"%#",[self removeCharsFrom:testName]];
filepathstring = [[self audioPathForResource:testName] retain];
NSLog(#"At start = %#",filepathstring);
if ([[NSFileManager defaultManager] fileExistsAtPath:filepathstring]) {
playBtn.enabled = YES;
trashBtn.enabled = YES;
recordBtn.enabled = YES;
}
else
{
playBtn.enabled = NO;
trashBtn.enabled = NO;
}
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
NSURL *soundFileURL = [NSURL fileURLWithPath:filepathstring];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
audioRecorder.delegate = self;
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[audioRecorder prepareToRecord];
}
}
- (void)viewDidUnload
{
[self setCancelBtn:nil];
[self setSaveBtn:nil];
[self setTimeLabel:nil];
[self setDescriptionLabel:nil];
[self setToolsBar:nil];
[self setTrashBtn:nil];
[self setPauseBtn:nil];
[self setRecordBtn:nil];
[self setPlayBtn:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return YES;
} else {
return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}
}
- (void)dealloc {
[cancelBtn release];
[saveBtn release];
[timeLabel release];
[descriptionLabel release];
[toolsBar release];
[trashBtn release];
[pauseBtn release];
[recordBtn release];
[playBtn release];
[audioPlayer release];
[audioRecorder release];
[super dealloc];
}
Here is the answer:
NSData *data = [NSData dataWithContentsOfMappedFile:[NSString stringWithFormat:#"%#",filepathstring]];
AVAudioPlayer *ap = [[AVAudioPlayer alloc]
initWithData:data error:&error];
Seems that it just wouldnt work with filepathstring but within an NSString it worked fine. Obvious now!

How to save value single time in database in iphone

i have an application in which i have 2 pages.one page is Register page and other is Login Page .
when a new user enter values in the register page and click on the submit the values are initially submitted to the server database.
When the same user come backs to the login page and enters his username and password and clicks on the submit button i get a JSON response on the console which returns the
{"TokenID":"fuUsat27to","isError":false,"ErrorMessage":"","Result":[{"UserId":"164","FirstName":"Indu","LastName":"nair","Email":"indu#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"22"}],"ErrorCode":900}
tokenID,USerID and DeviceID for every user and which are different for every user.
when the submit button is pressed on the login page all the values are saved in sqlite database.
In my login page i have 2 function first function checks that if user enter username and password and click on the submit button,the values should come from server if value is present in server .
If value is present in server database then it will take value from server and put all data in sqlite database.
This is all first time process for a new user.After all this happens the next function should be called.
In this function work is only to check username and password present in sqlite database .
If username and password is present then open the page otherwise show an error message.
-(void)check
{
app.journeyList = [[NSMutableArray alloc]init];
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [Uname.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [Password.text UTF8String], -1, SQLITE_TRANSIENT);
//NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
// NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
//NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
else {
isUserValid = YES;
if (isUserValid) {
app = (JourneyAppDelegate *)[[UIApplication sharedApplication]delegate];
TTabBar *tabbar=[[TTabBar alloc] init];
[app.navigationController pushViewController:tabbar animated:YES];
tabbar.selectedIndex = 0;
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
//this is used when the user first time log in the server and sends
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",Uname.text,Password.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
// this is to perfrom insert opertion on the userinformation table
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
//
BOOL errortest = [[result objectForKey:#"isError"] boolValue];
if(errortest == FALSE)
{
values = [result objectForKey:#"Result"];
NSLog(#"Valid User");
}
else
{
NSLog(#"Invalid User");
}
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
NSLog(#"%#",result.UserID);
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
//this four lines of code are for creating timestap and journeyID in userjourney table.
//NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
// NSLog(#"%#",timeStampObj);
// NSString *journeyid = [NSString stringWithFormat:#"%#_%#_%#", result.UserID, result.DeviceInfoId, timeStampObj];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [Uname.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [Password.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)buttonPressed:(id)sender
{
[[Reachability sharedReachability] setHostName:kHostName];
//Set Reachability class to notifiy app when the network status changes.
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
//Set a method to be called when a notification is sent.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
[self updateStatus];
[self sendRequest];
//NSLog(<#NSString *format#>)
//this is to select username and password from database.
[self check];
//Gpassq = Password.text;
//Gunameq = Uname.text;
//[self check];
}
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
}
- (void)updateStatus
{
// Query the SystemConfiguration framework for the state of the device's network connections.
self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
if (self.internetConnectionStatus == NotReachable) {
//show an alert to let the user know that they can't connect...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry, our network guro determined that the network is not available. Please try again later."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
} else {
// If the network is reachable, make sure the login button is enabled.
//_loginButton.enabled = YES;
}
}
It's very simple. First get your userName and all the values related to the user from Sqlite database on tap of submit button. If all the values found nil then you proceed with the server process. if all the values found in database proceed directly to next screen of the application.
EDIT
Pseudo Code-
- (IBAction)SubmitTapped:(id) sender {
//Check if Database already contains userName and password
if(userName && password){
//user name and password found in database
//show next screen or authenticate user through web services as per your requirement.
}
else {
//First time login
//Validate user entered data like values of textfields.(Suggestion use DHValidation for validating textfields)
BOOL validate = [self validateData];//a function to validate data using DHValidation create yourself.
if(validate){
//save login credentails into database
//show next screen
}
}
}
I hope you understand now.
UPDATE
-(void)check
{
app.journeyList = [[NSMutableArray alloc]init];
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [Uname.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [Password.text UTF8String], -1, SQLITE_TRANSIENT);
//NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
// NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
//NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
// [alert show];
// [alert release];
// alert = nil;
//we have no data into database so send request to webserver.
yourAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if(appDelegate.internetConnectionStatus != NotReachable){
//Network Available
[self sendRequest];
}
}
else {
isUserValid = YES;
if (isUserValid) {
app = (JourneyAppDelegate *)[[UIApplication sharedApplication]delegate];
TTabBar *tabbar=[[TTabBar alloc] init];
[app.navigationController pushViewController:tabbar animated:YES];
tabbar.selectedIndex = 0;
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
//this is used when the user first time log in the server and sends
-(void)sendRequest {
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",Uname.text,Password.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
// this is to perfrom insert opertion on the userinformation table
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
//
BOOL errortest = [[result objectForKey:#"isError"] boolValue];
if(errortest == FALSE)
{
values = [result objectForKey:#"Result"];
NSLog(#"Valid User");
}
else
{
NSLog(#"Invalid User");
}
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
NSLog(#"%#",result.UserID);
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
//this four lines of code are for creating timestap and journeyID in userjourney table.
//NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
// NSLog(#"%#",timeStampObj);
// NSString *journeyid = [NSString stringWithFormat:#"%#_%#_%#", result.UserID, result.DeviceInfoId, timeStampObj];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [Uname.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [Password.text UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)buttonPressed:(id)sender
{
//it should be on application did finish launching
[[Reachability sharedReachability] setHostName:kHostName];
//Set Reachability class to notifiy app when the network status changes.
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
//Set a method to be called when a notification is sent.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
//it will be called automatically you don't need to expilictly call this function
// [self updateStatus];
//The above code should be in application did finish launching.
//NSLog(<#NSString *format#>)
//this is to select username and password from database.
[self check];
//Gpassq = Password.text;
//Gunameq = Uname.text;
//[self check];
}
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
}
- (void)updateStatus
{
// Query the SystemConfiguration framework for the state of the device's network connections.
self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
if (self.internetConnectionStatus == NotReachable) {
//show an alert to let the user know that they can't connect...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry, our network guro determined that the network is not available. Please try again later."
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
} else {
// If the network is reachable, make sure the login button is enabled.
//_loginButton.enabled = YES;
}
}