how to set background color of range in TTTAtributedLabel - tttattributedlabel

Can't figure out how to set the background color of a range to make it look like a highlighter
The yellow color below does not show up as the background color
NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName, (id) NSBackgroundColorAttributeName, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:[UIColor redColor],[NSNumber numberWithInt:kCTUnderlineStyleNone], [UIColor yellowColor], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.madLibLabel.linkAttributes = linkAttributes;
[self.madLibLabel addLinkToURL:[NSURL URLWithString:#"what://"] withRange:[self.madLibLabel.text rangeOfString:#"WHAT"]];

You should use kTTTBackgroundFillColorAttributeName key instead NSBackgroundColorAttributeName.
Here is the code snippet:
NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName, (id) kTTTBackgroundFillColorAttributeName, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:[UIColor redColor],[NSNumber numberWithInt:kCTUnderlineStyleNone], [UIColor yellowColor], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.madLibLabel.linkAttributes = linkAttributes;
[self.madLibLabel addLinkToURL:[NSURL URLWithString:#"what://"] withRange:[self.madLibLabel.text rangeOfString:#"WHAT"]];

Related

How to create sqlite custom file in ios?

I am working on application where using local database as sqlite.
Where I want to create custom file for sqlite I don't know how to do this.
Any help would be appreciated.
First of all add below file into your project.
https://github.com/ConnorD/simple-sqlite
Then create database.sqlite file into your project. Database contain user first nam,last name and profile picutre.
And add below code into your AppDelegate file.
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"testing" message:#"path for database" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
// [alert release];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
//NSLog(#"Default writableDBPath: %#",writableDBPath);
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Category_DB.sqlite"];
//NSLog(#"Default : %#",defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// NSLog(#"Success");
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Call this method into your didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createEditableCopyOfDatabaseIfNeeded];
return NO;
}
Now write below code into your view controller where you want to use queries.
-(void)databaseOpen
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
myDatabase = [[Sqlite alloc] init];
[myDatabase open:myDBnew];
// NSLog(#"database opened");
}
For select query:
[self databaseOpen];
NSString *query_fetch=[NSString stringWithFormat:#"select Max(session_id) from Report"];
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
IF you want to save image to database
-(NSString *) getImagePath{
/* *** Modify on 16 01 2012 by Prerak *** */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
return documentsDirectory;
}
IF you want to get image to database
arrProfilepic = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath error:&error];
NSLog(#"File Path Array is %#",filePathsArray);
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingString:#"/"] stringByAppendingString:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
//NSLog(#"Data %#", data);
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"Image %#", image);
[arrProfilepic addObject:image];
}
}
}
NSLog(#"profile is %#",arrProfilepic);
For Insert query:
NSString *documentsDirectory = [self getImagePath];//save image to database
NSString *imagePath;
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"User_%d.png",newid]];
NSString *relativePathImage1=nil;
NSArray *relativeArray=[imagePath componentsSeparatedByString:#"/Documents"];
UIImage *thumbImage;
thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)];
NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f);
[thumbData writeToFile:imagePath atomically:YES];
NSString *query_insert=[NSString stringWithFormat:#"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%#','Smith','%#')",newid,VcAddUser.txtFUsername.text,relativePathImage1];
NSMutableArray *userData=[[NSMutableArray alloc]init];
userData=[[myDatabase executeQuery:query_insert];
[database close];
For Delete query:
NSString *query_user=[NSString stringWithFormat:#" delete from UserDetails where User_id=%d",Userid];
[myDatabase executeNonQuery:query_user];
[myDatabase close];
**For Update query:**
NSString *updatequery=[NSString stringWithFormat:#"Update UserDetails set User_fname='%#',User_lname='%#', User_image='%#' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate];
[myDatabase executeNonQuery:updatequery];
// NSLog(#"Query user is %#",updatequery);
[myDatabase close];
For Webservices
-(void) CallWebservice
{
NSMutableData *responseData = [NSMutableData data];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"give your web service url"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self removeProgressIndicator];
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// check for response only
/*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);*/
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}

how to pass image to a web service in string format from xcode

+(id)profilePictureUploadWebService :(NSString*)temp andimage:(NSString*)strimage
{
//NSString *post=[NSString stringWithFormat:#"_UserId=%#&_UserImage=%#",temp,strimage];
NSString *post=#"";
NSString *urlTotal= [ NSString stringWithFormat:#"http://mo.sale.com/as.asmx/SaveUserImage?_UserId=%#&_UserImage=%#",temp,strimage];
NSURL *url= [ NSURL URLWithString:urlTotal];
NSLog(#"urlTotal is =%#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data is =%#",data);
return (urlData);
}

UIImageView array

How to put four images in a UIImageView array?
why my forloop can't run?
if i want to create four frames with four images,how to do that?
NSArray *photos = [NSArray arrayWithObjects:
[UIImage imageNamed:#"1.jpg"],
[UIImage imageNamed:#"2.jpg"],
[UIImage imageNamed:#"3.jpg"],
[UIImage imageNamed:#"4.jpg"],nil];
for(int i=0;i<5;i++)
{
UIImage *image = [UIImage imageNamed:[photos objectAtIndex:i]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
}
NSArray *photos = [NSArray arrayWithObjects:
[UIImage imageNamed:#"1.jpg"],
[UIImage imageNamed:#"2.jpg"],
[UIImage imageNamed:#"3.jpg"],
[UIImage imageNamed:#"4.jpg"],nil];
UIImageView *imgView = [[UIImageView alloc]init];
imgView.animationImages = photos;
[photos objectAtIndex:i] this method you get the UIImage object only , you can't get a NSString object for [UIImage imageNamed:] method.

How to add NavigationController into Tabbed Based Application in iOS

I'm using Xcode 4.4.1. I have created a simple tabbed based application. And then I want to add navigation controller to the application. Can any one tell me how to do that in Xcode 4.4.1. My current code is like this but it doesn't work.
`
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[Addbills alloc]initWithNibName:#"Addbills" bundle:nil];
UIViewController *viewController3 = [[CalenderView alloc]initWithNibName:#"CalenderView" bundle:nil];
UIViewController *viewController4 = [[Web alloc]initWithNibName:#"Web" bundle:nil];
UIViewController *viewController5 = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController1];
[self.navigationController setNavigationBarHidden:TRUE];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = #[viewController1,viewController2,viewController3,viewController4,viewController5];
self.window.rootViewController = self.tabBarController;
// self.window.rootViewController =self.navigationController;
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
`
and this is my button click event in viewController5
`
- (IBAction)backToPrevious:(id)sender {
[self.navigationController popToRootViewControllerAnimated:TRUE];
}`
Thanks,
Here is how you should do it.
// initialize the tabbar controller
UITabBarController *tabbarController = [[[UITabBarController alloc] init] autorelease];
UIViewController *itemsViewController1 = [[[UIViewController alloc] initWithNibName:#"SomeViewController1" bundle:nil] autorelease];
UINavigationController *itemsNavigationController1 = [[UINavigationController alloc] initWithRootViewController:itemsViewController1];
UIViewController *itemsViewController2 = [[[UIViewController alloc] initWithNibName:#"SomeViewController2" bundle:nil] autorelease];
UINavigationController *itemsNavigationController2 = [[UINavigationController alloc] initWithRootViewController:itemsViewController2];
tabbarController.viewControllers = #[itemsNavigationController1,itemsNavigationController2];
_window.rootViewController = tabbarController;

converting NSString to NSURL from a plist file

I've been trying to get a string from a plist file into a NSURL for webview.
Either i get 'nil' for the returned value, or nothing (no error in console)
I know something's wrong with this code, but i can't pinpoint it where.
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *value;
value = [plistDict objectForKey:#"Link"];
NSString *webStringURL = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:webStringURL];
[self loadURL:URL];
[self setURLToLoad:nil];
Where did i mess up?
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *urlString = [plistDict objectForKey:#"Link"];
NSURL *URL = [NSURL URLWithString:urlString];
[self loadURL:URL];
For your better understanding refer to this site:
http://iphonesdevsdk.blogspot.com/2011/04/plist.html
It may help you in using plist in easy way.

Resources