Download sqlite database from URL - objective-c

I'm using this code the load the local sqlite database.
- (id)init
{
self = [super init];
if (self) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"db" ofType:#"sqlite3"];
_db = [[MDDatabase alloc] initWithPath:path];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
I would like to put the database online and let the app download the database instead. I changed the code to:
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
Editted:
I changed my code to follow but it's crashed.
- (id)init
{
self = [super init];
if (self) {
[self performSelectorOnMainThread:#selector(downalod) withObject:nil waitUntilDone:YES];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
-(void)download
{
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
}

You have problem in your file. Check with correct url. Its an encoding issue. Try with this (It will work) : http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg
Add App Transport Security Settings (Allow Arbitrary Loads YES) in your plist.
Enable background mode.
Declare this macro in .m
#define DocumentsDirectory [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
Now call and you will have the file in your local.
Call like:
[self performSelectorOnMainThread:#selector(downalod) withObject:nil waitUntilDone:NO];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
-(void)download
{
NSString *stringURL =[NSString stringWithFormat: #"url"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *filePath = [DocumentsDirectory stringByAppendingPathComponent:[url lastPathComponent]];
NSLog(#"success--222,%#", filePath);
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"success--222,%#", filePath);
if (error)
{
NSLog(#"success--not---Error,%#", [error localizedDescription]);
}
else
{
NSLog(#"success--yes... %#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
[data writeToFile:filePath atomically:YES];
}
}];
}

After long time search, finally I solved it myself:
- (id)init
{
self = [super init];
if (self) {
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/db.sqlite3"]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"db.sqlite3"];
[fetchedData writeToFile:filePath atomically:YES];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}

Related

how to zip and email a file using objective c?

I need to zip my log file and email it. I'm using Objective-zip for zipping my file. And this is my code
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"test.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
//OZZipFile *readFile = [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"Logfile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"test.zip"];
[self presentViewController:mc animated:YES completion:nil];
[zipFile32 close];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Aglive Pro" message:#"You have not configured your mail account. Please configure your mail account from the device settings." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
right now I'm able to send a zip file in email but when I do unzip and open the file in my mobile or mac I get alert saying that The document “Logfile 4.txt” could not be opened. The file isn’t in the correct format. I don't know where I'm going wrong.
This code worked for me
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Logfile.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
//NSData *zipdata2 = [NSData dataWithContentsOfFile:zipFile32];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"LogFile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
[zipFile32 close];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
//
if(zipdata== 0 && zipdata==nil)
{
[self mailLogFile];
}
else
{
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"Logfile.zip"];
[self presentViewController:mc animated:YES completion:nil];
}

How do I generate thumbnail of map using given Lat/Long in iOS?

I am working on a chat application where I am going to send a map to another user.
Below is my code to generate a thumbnail of a map. Is there any way to generate a map thumbnail in Objective-C?
Code to generate thumbnail of static map:
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:blue|%#,%#&%#&sensor=true",_lat, _longi,#"zoom=13&size=%dx%d"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
Save thumbnail images in document directories:
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
Send thumbnail data to bubble to display thumbnail:
NSBubbleData *MapSendBubble = [NSBubbleData dataWithImage:mapImage date:[NSDate date] type:BubbleTypeMine];
MapSendBubble.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:MapSendBubble];
[_bubbleTable reloadData];
Send map:
NSDate *today=[NSDate date];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"YYYYMMddhhmmss"];
NSString *dateString1=[dateFormat1 stringFromDate:today];
NSString *userid= #"mc1"; NSString *latlong=[NSString stringWithFormat:#"%#%#",[_lat substringToIndex:2],[_longi substringToIndex:2]];
[map setTag:[[NSString stringWithFormat:#"%#",latlong] integerValue]];
NSString *longlat=[NSString stringWithFormat:#"%#,%#",_longi,_lat];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSString *date=[dateFormat stringFromDate:[NSDate date]];
//Find a cache directory. You could consider using documents dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSError *error;
NSString *MainFolder = [path stringByAppendingPathComponent:[NSString stringWithFormat:#"/SmoothChat"]];
NSString *Locations=[MainFolder stringByAppendingPathComponent:[NSString stringWithFormat:#"/Locations"]];
if (![[NSFileManager defaultManager] fileExistsAtPath:MainFolder])
{
[[NSFileManager defaultManager] createDirectoryAtPath:MainFolder withIntermediateDirectories:NO attributes:nil error:&error];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:Locations])
{
[[NSFileManager defaultManager] createDirectoryAtPath:Locations withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:red|%#,%#&%#&sensor=true",_lat,_longi,#"zoom=15&size=300x180"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
// NSString *uuid1 = [[NSUUID UUID] UUIDString];
// [self sendXMPPMessage:1 :[NSString stringWithFormat:#"lc%#",value] :[NSString stringWithFormat:#"oi_%#_lc_%#.jpg",userid,dateString1] :#"" :jsonstring :[NSString stringWithFormat:#"%#",longlat] :_user :#"" :#"" :#"" :[[NSUserDefaults standardUserDefaults] stringForKey:#"current_chat"] :#"" :#"" :_senderType :[self currentDateTme] :0];
NSBubbleData *photoBubble11 = [NSBubbleData dataWithImage:staticMapUrl date:[NSDate date] type:BubbleTypeMine];
photoBubble11.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:photoBubble11];
[_bubbleTable reloadData];
[self goToBottom];
[map setHidden:YES];
[blurView setHidden:YES];
[_NewView setHidden:YES];
[map removeAnnotation:point];
currentLocation=nil;
[locationManager stopUpdatingLocation];

How to play audio file of URL link using AVAudioPlayer in iphone objective-c

I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
testing I am experiencing an error with playing back message I created
with AVAudioPlayer. The AVAudioplayer just returns a null value.
How do I play an audio file from the URL link with AVAudioPlayer?
if (!self.audioRecorder.recording) {
NSURL *url = [NSURL URLWithString:[#"http://.../sound.mp4"]];
NSLog(#"%#", url);
NSLog(#"PlayBack");
NSData *audioData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound1.caf"];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
if (self.audioPlayer == nil) {
NSLog(#"%#", [error description]);
NSLog(#"%#", [self.audioPlayer description]);
}else
[self.audioPlayer play];
}else [self.audioRecorder stop];
please try out this code:
- (void) playMessageSound : (NSString *) filename{
self.soundFilename = filename;
//[[RBDMuteSwitch sharedInstance] detectMuteSwitch];
NSString *name = [filename stringByDeletingPathExtension];
NSString *extension = [filename pathExtension];
NSString *filePath = [[NSBundle mainBundle]pathForResource:name ofType:extension];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0;
[self.audioPlayer play];
}
check this
NSString* resourcePath = #""; //your url
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
NSError *error;
app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
app.audioPlayer.numberOfLoops = 0;
app.audioPlayer.volume = 4.0f;
[app.audioPlayer prepareToPlay];
if (app.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[app.audioPlayer play];

How to attach image in vCard (vcf file) using Objective C?

In my project I need to create and send a vCard (vcf file) that must include an image too. I did everything right except I can not add image to the vCard. I have shared my code below.
- (IBAction)shareButtonPressed:(UIButton *)sender {
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"vCard.vcf"];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeMessage, UIActivityTypeCopyToPasteboard];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"Rokon"], 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", #"Rokon"]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",#"+8801811536248"]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64:%#",[imageData base64EncodedDataWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
- (void)shareContact{
[self emptySandbox];
NSString *contactName = [NSString stringWithFormat:#"%# %#",[Person sharedInstance].firstName, [Person sharedInstance].lastName];
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.vcf", contactName]];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[contactName, [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard];
[activityVC setValue:contactName forKey:#"subject"];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([Person sharedInstance].profileImage, 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", [NSString stringWithFormat:#"%#%#", [Person sharedInstance].firstName, [Person sharedInstance].lastName]]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",[Person sharedInstance].phone]];
[mutableArray addObject:[NSString stringWithFormat:#"email:%#", [Person sharedInstance].email]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64;ENCODING=b;TYPE=JPEG:%#",[imageData base64EncodedStringWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
-(void)emptySandbox
{
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
while (files.count > 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
for (NSString *path in directoryContents) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
if (!removeSuccess) {
// Error
}
}
} else {
// Error
}
}
}

How to set a default user in xcode7 with the help of objective c?

I'm trying to build and login and logout application, but not able to login please help me to set default user id and password through which i would be able go to the next page
You can try this code it will help you :
-(void)login
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/pm/api/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
if(checkBoxSelected == YES)
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernameField.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordField.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self.navigationController pushViewController:i animated:YES];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected;
[checkbox setSelected:checkBoxSelected];
}
to set a default user in app you may use the code below
In your AppDelegate.m
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"IsFirstTime"])
{
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = vc;
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
then #import your AppDelegate.m class to the class where you put code for login
AppDelegate *delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
}
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://43.252.88.251/jsonandroid/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernamefield.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordfield.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
/* ItemManagement *ItemManagement = [[ItemManagement alloc]init];
[self.navigationController pushViewController:ItemManagement animated:YES];
*/
}
else
{
NSLog(#"Unsuccessful, Try again.");
/* UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];*/
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"Hello" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelbutton = [UIAlertAction actionWithTitle:#"" style:UIAlertActionStyleCancel handler:nil];
//UIAlertAction *oktext= [UIAlertAction actionWithTitle:oktext style:UIAlertActionStyleDefault handler:nil];
[alert addAction:cancelbutton];
//[alert addAction:oktext];
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}