Monday, June 18, 2012

UIView class methods for common animations.



Following  UIView class  methods are convenience methods for common animations.

UIView Animation blocks

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.70];
[UIView setAnimationDelay:0.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        
Your Code to change the position of UIVeiw goes here...
        
[UIView commitAnimations];


We can animate UIView in ios 5 using this simple code. 

[UIView animateWithDuration:0.5
                              delay:1.0
                            options: UIViewAnimationCurveEaseOut
                         animations:^{
                             view.contentOffset = CGPointMake(position, 0.0f);
                         }
                         completion:^(BOOL finished){
                             NSLog(@"Done!");
                         }];

Wednesday, June 13, 2012

Method to insert text to a UITextView.


Method to insert text to a UITextView.

- (void)insertTextToTextView:(NSString *)string
{
    if ([self.textView.text length]== 0)// Nothing in the textview
    {
        NSString *textViewString = [[NSString alloc] initWithFormat:@"%@%@",textView.text, string];
        [textView setText:textViewString];
    }
    else
    {
        NSRange range = textView.selectedRange;
        NSString *firstHalfString = [textView.text substringToIndex:range.location];
        NSString *secondHalfString = [textView.text substringFromIndex:range.location];
        textView.text = [NSString stringWithFormat:@"%@%@%@",firstHalfString,string,secondHalfString];
        textView.selectedRange = NSMakeRange(firstHalfString.length+string.length,0);
       
    }
}

QuartzCore Framework

If You get this kind of compile error,

Property 'anchorPoint' cannot be found in forward class object 'CALayer'

Solution:

Most likely, the error is caused because the QuartzCore  Framework is not added to the project.

To do this, select the project in the left sidebar and then select Target and then the Build Phases tab on the right pane. Expand the “Link Binary with Libraries” section and then click on the + sign and look for QuartzCore to add it.

Don't forget to Import the QuartzCore to your .m file.

Use this code. #import <QuartzCore/QuartzCore.h>

Done. :)

Friday, December 2, 2011

Method to dynamically set the height of UILabel, UITableViewCell etc

To find the height of a label , UITableViewCell or UITextView for dynamic string content. Following method may help


- (float)getHeightFortheDynamicLabel:(NSString *)stringForTheLabel{
    UITextView *aSampleTextView;
    // 30 is the minimum height
    aSampleTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, mywidth, 30)];
    aSampleTextView.text = stringForTheLabel;
    aSampleTextView.font = [UIFont systemFontOfSize:kMyFontSize];
    aSampleTextView.alpha = 0;
    [self.view addSubview:aSampleTextView];
    float textViewHeight = aSampleTextView.contentSize.height;
    [aSampleTextView removeFromSuperview];
    [aSampleTextView release];
    return  textViewHeight;
}

Friday, November 25, 2011

Programmatically calling to a phone number from iPhone.

//  This method will call a phone number from string.
+ (void)callPhoneNumber:(NSString *)phoneNumberString
{
        if ([phoneNumberString length]>0)
        {
            phoneNumberString = [[phoneNumberString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];
            NSString *phoneDecender = @"tel:";
            NSString *totalPhoneNumberString = [phoneDecender stringByAppendingString:phoneNumberString];
            NSURL *aPhoneNumberURL = [NSURL URLWithString:totalPhoneNumberString];
       
            if ([[UIApplication sharedApplication] canOpenURL:aPhoneNumberURL])
            {
                    [[UIApplication sharedApplication] openURL:aPhoneNumberURL];
            }
       
        }
}

Applying Java script to UIWebView from Objective C - iPhone SDK

//------------------------------------------------------------------------------------------------------------ 
/*Java script code */
function switchFontsize(val)
{
    if(val)
    {
         document.getElementById("myDivId").style.fontSize = val + "px";
         document.getElementById("mySecondDivId").style.fontSize = val + "px";
    }
}
//-------------------------------------------------------------------------------------------------------------
/* Objective C function to apply font to the web view */
+ (void)applyFontToWebView:(UIWebView *)webView withFontSize:(int)fontSize
{
    NSString *jsString = [NSString stringWithFormat:@"switchFontsize(%d)",fontSize];
    [webView stringByEvaluatingJavaScriptFromString:jsString];
}
//-------------------------------------------------------------------------------------------------------------
/* Function to call when font plus button press event */
- (void)increaseFont
{
    // 24 is set as the maximum font size.
    if (currentFontSize < 24)
    {
        currentFontSize = currentFontSize + 2;
    }
    [FontClass applyFontToWebView:self.webView withFontSize:currentFontSize];
}

Note - Make sure that you are calling the java script file in the html string loaded in the webview.

Tuesday, May 31, 2011

Validating UITextView For Minimum Text Length

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

if (([text length] == 0)&& ([textView.text length] ==1))
{
self.sendButton.enabled = NO;
}
else if ([text length] == 1)
{
self.sendButton.enabled = YES;
}

return YES;
}

Friday, January 14, 2011

NSXMLParserErrorDomain error 68

If you get this kind of parsing error,

NSXMLParserErrorDomain error 68 or called as 'NSXMLParserNAMERequiredError'

Reason :- Most likely, the error is caused because the xml data you are parsing. in the xml there will be some special characters that are not encoded.

Example :- character '&' did not show up as '&amp'

That is what the error means: Parser is expecting an input for that assuming '&' as a element.

Solution :- Change the xml.

For more details :- NSXMLParser Class Reference

Thanks

Sunday, January 2, 2011

Creating a POST request and downloading the data. - iOS SDK

NetCommunicator.m

@implementation NetCommunicator

@synthesize myFeedConnection,myReceivedData;

-(void)createPostRequestWith:(NSString *)username andPassword:(NSString *)password {

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",username,password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"www.yourwebpage.com"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

self.myFeedConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

// Test the validity of the connection object. The most likely reason for the connection object
// to be nil is a malformed URL, which is a programmatic error easily detected during development
// If the URL is more dynamic, then you should implement a more flexible validation technique, and
// be able to both recover from errors and communicate problems to the user in an unobtrusive manner.
//

NSAssert(self.myFeedConnection != nil, @"Failure to create URL connection.");

// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}



#pragma mark -
#pragma mark NSURL Connection Delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

if (connection == self.myFeedConnection) {
self.myReceivedData = [NSMutableData data];
}

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

if (connection == self.myFeedConnection) {

[self.myReceivedData appendData:data];
}

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

if (connection == self.myFeedConnection) {
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfo];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
// release our connection
self.myFeedConnection = nil;
}

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

if(connection == self.myFeedConnection) {

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

NSLog(@"my Data: %.*s", [self.myReceivedData length], [self.myReceivedData bytes]);

// Do the rest with the downloaded data.

self.myFeedConnection = nil;

}

}


// -------------------------------------------------------------------------------
// handleError:error // This method should be modified ..
// -------------------------------------------------------------------------------
- (void)handleError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot download"
message:errorMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}


@end

Tuesday, November 2, 2010

Core Data - Compile error

If You get this kind of compile error,

"_OBJC_CLASS_$_NSManagedObjectContext", referenced from:
objc-class-ref-to-NSManagedObjectContext in AppDelegate.o

"_OBJC_CLASS_$_NSEntityDescription", referenced from:
objc-class-ref-to-NSEntityDescription in AppDelegate.o

"_NSSQLiteStoreType", referenced from:
_NSSQLiteStoreType$non_lazy_ptr in AppDelegate.o
(maybe you meant: _NSSQLiteStoreType$non_lazy_ptr)


"_OBJC_CLASS_$_NSPersistentStoreCoordinator", referenced from:
objc-class-ref-to-NSPersistentStoreCoordinator in AppDelegate.o

"_OBJC_CLASS_$_NSFetchRequest", referenced from:
objc-class-ref-to-NSFetchRequest in AppDelegate.o

"_OBJC_CLASS_$_NSManagedObjectModel", referenced from:
objc-class-ref-to-NSManagedObjectModel in AppDelegate.o
ld: symbol(s) not found

collect2: ld returned 1 exit status


Solution:
Most likely, the error is caused because the Core Data Framework is not added to the project.

Right click Frameworks folder -> Add -> Existing Frameworks -> CoreData.framework.

Done. :)