UITextField not saving text - iphone

I have a view with several UITextFields in it. I also have a high level UISegmentController that changes the view. When I enter text in a field, then press the hide keyboard button, then change segemnents, it saves fine. But when I enter text, and don't press the release keyboard button, then switch segments, it does not save the text.
How can I fix this?
Here is some of the code for the UITextField in my custom UITableViewCell:
- (IBAction)col2_doubleValueChanged:(id)sender
{
NSString *newValue = [NSString stringWithFormat:#"%#/%#", self.col2_doubleEntryValue_1.text, self.col2_doubleEntryValue_2.text];
NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
[result setValue:self.row_key forKey:#"row_key"];
[result setValue:#"1" forKey:#"column"];
[result setValue:newValue forKey:#"col2_value"];
[[self delegate] editDidFinish:result];
[[self delegate] valueChanged];
}
- (IBAction)col2_singleValueEditDidBegin:(id)sender
{
}
Edit:
- (void)valueChanged
{
self.dirtyFlag = 1;
}
- (int)saveDataToServer
{
[self.tableView resignFirstResponder];
if (!dirtyFlag) {
return 0;
}
NSString *errors = [DataSource updatePatientWorkflowClinicalChecklistForAppointment:[[[DrChronoDataSource getCurrentAppointment] valueForKey:#"appointment_id"] intValue] clinicalInfo:self.clinicalChecklist checklistId:[self.clinicalChecklistId intValue] patientWorkflowServerId:patientWorkflowServerId];
if ((NULL == errors) || ![errors isEqualToString: #""]) {
//Show error messages.
if (NULL == errors) {
errors = #"Failed to save data to server. Please retry.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Status" message:errors delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return -1;
} else {
[self dismissModalViewControllerAnimated:FALSE];
}
self.dirtyFlag = 0;
return 0;
}

You do not have any writing functions.
- (IBAction)col2_doubleValueChanged:(id)sender
{
NSString *newValue = [NSString stringWithFormat:#"%#/%#", self.col2_doubleEntryValue_1.text, self.col2_doubleEntryValue_2.text];
NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
[result setValue:self.row_key forKey:#"row_key"];
[result setValue:#"1" forKey:#"column"];
[result setValue:newValue forKey:#"col2_value"];
/* your aren't writing the new data anywhere,
you need to add something like this:
*/
[result writeToFile: #"somefile.txt" atomically: YES];
[[self delegate] editDidFinish:result];
[[self delegate] valueChanged];
}

Couldn't you link both events to the same action? Maybe you could make a BOOL in your header file called needsSaving. Set it to NO every time editing begins, then YES every time the data is saved successfully. Then only execute the body of your saving methods if needsSaving is NO, that will avoid unnecessary saving. I think doing this would simplify this function of your app. i.e.
- (IBAction)col2_singleValueEditDidBegin:(id)sender {
needsSaving = YES;
}
- (int)saveDataToServer
{
[self.tableView resignFirstResponder];
if (!dirtyFlag || !needsSaving) {
return 0;
}
NSString *errors = [DataSource updatePatientWorkflowClinicalChecklistForAppointment:[[[DrChronoDataSource getCurrentAppointment] valueForKey:#"appointment_id"] intValue] clinicalInfo:self.clinicalChecklist checklistId:[self.clinicalChecklistId intValue] patientWorkflowServerId:patientWorkflowServerId];
if ((NULL == errors) || ![errors isEqualToString: #""]) {
//Show error messages.
if (NULL == errors) {
errors = #"Failed to save data to server. Please retry.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Status" message:errors delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return -1;
} else {
needsSaving = NO;
[self dismissModalViewControllerAnimated:FALSE];
}
self.dirtyFlag = 0;
return 0;
}

Looks to me like you are not implementing the UITextFieldDelegate prototocols.

Related

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.

detecting youtube video links programmatically in Objective-C

I need to download and save videos from video sites like youtube. I want to save them to the video library of the iPhone. How can I detect the videos and save them to library? I already checked out some source codes available. This is what i have done in the download action, but is not working.
- (IBAction)download {
[downloadButton setEnabled:NO];
[webView setUserInteractionEnabled:NO];
UIUserInterfaceIdiom userInterfaceIdiom = [UIDevice currentDevice].userInterfaceIdiom;
NSString *getURL = #"";
if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
getURL = [webView stringByEvaluatingJavaScriptFromString:#"function getURL() {var player = document.getElementById('player'); var video = player.getElementsByTagName('video')[0]; return video.getAttribute('src');} getURL();"];
} else {
getURL = [webView stringByEvaluatingJavaScriptFromString:#"function getURL() {var bh = document.getElementsByClassName('bh'); if (bh.length) {return bh[0].getAttribute('src');} else {var zq = document.getElementsByClassName('zq')[0]; return zq.getAttribute('src');}} getURL();"];
}
NSString *getTitle = [webView stringByEvaluatingJavaScriptFromString:#"function getTitle() {var jm = document.getElementsByClassName('jm'); if (jm.length) {return jm[0].innerHTML;} else {var lp = document.getElementsByClassName('lp')[0]; return lp.childNodes[0].innerHTML;}} getTitle();"];
NSString *getTitleFromChannel = [webView stringByEvaluatingJavaScriptFromString:#"function getTitleFromChannel() {var video_title = document.getElementById('video_title'); return video_title.childNodes[0].innerHTML;} getTitleFromChannel();"];
NSLog(#"%#, %#, %#", getURL, getTitle, getTitleFromChannel);
[webView setUserInteractionEnabled:YES];
NSArray *components = [getTitle componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
getTitle = [components componentsJoinedByString:#" "];
if ([getURL length] > 0) {
if ([getTitle length] > 0) {
videoTitle = [getTitle retain];
bar = [[UIDownloadBar alloc] initWithURL:[NSURL URLWithString:getURL]
progressBarFrame:CGRectMake(85.0, 17.0, 150.0, 11.0)
timeout:15
delegate:self];
[bar setProgressViewStyle:UIProgressViewStyleBar];
[toolbar addSubview:bar];
} else {
NSArray *components = [getTitleFromChannel componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
getTitleFromChannel = [components componentsJoinedByString:#" "];
if ([getTitleFromChannel length] > 0) {
videoTitle = [getTitleFromChannel retain];
bar = [[UIDownloadBar alloc] initWithURL:[NSURL URLWithString:getURL]
progressBarFrame:CGRectMake(85.0, 17.0, 150.0, 11.0)
timeout:15
delegate:self];
[bar setProgressViewStyle:UIProgressViewStyleBar];
[toolbar addSubview:bar];
} else {
//NSLog(#"%#", [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML;"]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"MyTube" message:#"Couldn't get video title." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
[downloadButton setEnabled:YES];
}
}
} else {
//NSLog(#"%#", [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML;"]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"MyTube" message:#"Couldn't get MP4 URL." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
[downloadButton setEnabled:YES];
}
}
This will grab the video ids if you are consistently expecting they to be in the < object > format.
Regex will obviously need to be changed if it's in an iframe.
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"<object .*name=\"movie\" value=\"[a-zA-z:\\/]*.com\\/\\w*\\/([A-Za-z0-9\\_-]*).*<\\/object>"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:pageSource options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSString *videoID = [pageSource substringWithRange:[match rangeAtIndex:1]];
}];
You can save downloaded videos either to photos album or to the app directory itself.For downloading videos u have to generate a downloadble link of the corresponding video.In the case of downloading videos from the site youtube,refer this source code https://github.com/comonitos/youtube_video. Some sites are download restricted ones that may not be possible.In the case of all other sites by generating the downloadable url,you can make it work

Separating a string?

- (IBAction)doUpload:(id)sender {
NSMutableString *str = [[NSMutableString alloc] initWithString:#"Selected: "];
for(int i = 0; i < [appDelegate.notesArray count]; i++) {
// UPLOAD STRINGS HERE
if(selected[i]) {
[str appendFormat:#"%# ", [appDelegate.notesArray objectAtIndex:i]];
}
}
UploadView *uploadview = (UploadView *)self.view;
if(uploadview != nil) {
[m_owner uploadString:str];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Selected Values" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
// [self dismissModalViewControllerAnimated:YES];
}
}
In the above code, the str variable contains some values from the tableview cell. My tableview has multiple selection enabled, so str contains multiple values.
This code:
[m_owner uploadString:str];
is used for uploading to gdoc, but when str contains multiple values, it uploads all the values at the same time. I want to separate the values, and then upload them one by one.
How can I do this?
NSString *str = #"Hi ! I am iPhone Developer";
NSArray *myWords = [str componentsSeparatedByString:#"!"];
NSString *str1 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:0]];
NSString *str2 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:1]];
NSLog(#"%#",str1);
NSLog(#"%#",str2);
You will find in Log like this
Hi
I am iPhone Developer
If you just want to separate the components you can try using the componentsSeperatedByString: method. As a result you will be getting an array of objects which you can use to iterate for uploading.
[yourString componentsSeparatedByString:separatorString];
hope this helps.

Application crashing at Loading UIalertview indicator while loading data in iphone

I am calling URL on my Search button event to load data. I have put the code for Loading indicator Alert view by taking NSThread. I am using 3.2 xcode with 4.3 iOS. Every thing run smooth but on search button it shows Loading indicator and then crashing and showing following in console
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
Code under the Search Button click event:
- (IBAction) searchButton {
if([addressField.text length]==0)
{
UIAlertView *myAlert = [[[UIAlertView alloc] initWithTitle:#"Alert" message:#"Please Tap on 'Show Me' & choose the 'Radius' first!!!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil] autorelease];
[myAlert show];
}
else
{
[NSThread detachNewThreadSelector:#selector(updateFilterProgress) toTarget:self withObject:nil];
appDelegate = (MapTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
CLLocationCoordinate2D location;
float radius = [[arrayNo objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue];
NSString *url = [NSString stringWithFormat:#"http://....url...../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
NSLog(#"%#", url);
NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
{
if([appDelegate.markers count] == 0){
UIAlertView *myAlert = [[[UIAlertView alloc] initWithTitle:#"Alert" message:#"No results fond!!!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil] autorelease];
[myAlert show];
}
else
{
resultButton.userInteractionEnabled = YES;
for (int i = 0; i < [appDelegate.markers count]; i++)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
location.latitude = [aMarker.lat floatValue];
location.longitude =[aMarker.lng floatValue];
AddressAnnotation *annob = [[AddressAnnotation alloc] initWithCoordinate:location];
annob.title = aMarker.name;
annob.subTitle = aMarker.address;
[mapView addAnnotation:annob];
[annob release];
CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude}; //for zoom in the showroom results region
MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
NSLog(#"No Errors");
mapView.region = ausRegion;
}
}
}
else
NSLog(#"Error Error Error!!!");
[addressField resignFirstResponder];
}
}
And for NSThread to Show Loaading indicator while loading data at the back.
- (void) updateFilterProgress{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *myAlert = [[[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"This app require an internet connection via WiFi or cellular network to work." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil] autorelease];
[myAlert show];
}
else{
UIAlertView *alertMe = [[[UIAlertView alloc] initWithTitle:#"Loading..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alertMe show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
// Adjust the indicator so it is up a few pixels from the bottom of the alert
indicator.center = CGPointMake(alertMe.bounds.size.width / 2, alertMe.bounds.size.height - 50);
[indicator startAnimating];
[alertMe addSubview:indicator];
[indicator release];
[alertMe release];
for (int i = 200; i > [appDelegate.markers count]; i--)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
[alertMe dismissWithClickedButtonIndex:0 animated:YES];
}
}
[pool release]; }
Is there anything remaining in my code. Pleas correct me....
The variable alertMe is autoreleased and therefore you can't just send a release message to it. Remove the line [alertMe release]; and it will run perfectly.
You are probably accessing a released object. To see which one it is, set NSZombiesEnabled - this will show you which already released object you try to access, and you should be able to identify your problem.
Please have a look here to see how to enable the zombies in XCode 4:
http://42games.net/quick-note-on-setting-nszombieenabled-environment-variable-in-xcode-4/

Customized Annotation

i have a question regarding customized annotation here. Here is how i show the pin but i wish to insert an image in to the annotation when the user click on the pin. how can i do that?
- (void) showMarkingOnMap:(Service *) ser
{
if (!self.mapView.loaded) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iPoly"
message:#"Failed to load the map."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
return;
}
id<AGSLayerView> graphicsLayerView = [self.mapView.mapLayerViews objectForKey:#"GraphicsLayer"];
AGSGraphicsLayer *graphicsLayer = (AGSGraphicsLayer*)graphicsLayerView.agsLayer;
[graphicsLayer removeAllGraphics];
// Create a symbols png graphic
AGSPictureMarkerSymbol *genSymbol = [AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:#"pushpin.png"];
ServiceInfoTemplate *infoTemplate = [[ServiceInfoTemplate alloc] init];
AGSGraphic *genGraphic;
AGSPoint *genPt;
NSMutableDictionary *dic= [[NSMutableDictionary alloc] init];
[dic setObject:[ser name] forKey:#"NAME"];
if([ser.location isEqualToString: #"\n"] || (ser.location == nil)){
[dic setObject:#"" forKey:#"DESC"];
} else {
[dic setObject:[ser location] forKey:#"DESC"];
}
genPt = [AGSPoint pointWithX:[[ser xcoordinate] floatValue]
y:[[ser ycoordinate] floatValue]
spatialReference:self.mapView.spatialReference];
genGraphic = [[AGSGraphic alloc] initWithGeometry:genPt symbol:genSymbol attributes:dic infoTemplateDelegate:infoTemplate];
[graphicsLayer addGraphic:genGraphic];
[graphicsLayer dataChanged];
[self.mapView zoomWithFactor:0.1 atAnchorPoint:genPt.cgPoint animated:NO];
[self.mapView centerAtPoint:genPt animated:YES];
//CGPoint *pt = CGPointMake([[ser ycoordinate] floatValue], [[ser xcoordinate] floatValue]);
}
It's not as easy as you might hope/think. Here's a full tutorial on how to do it.
Note that with this implementation, your callout will occupy the entire width of the view.
See:
http://blog.asolutions.com/2010/09/building-custom-map-annotation-callouts-part-1/