absoluteString "handleOpenURL " to match email attachment name? - xcode

I have a working code, but now find the need to import & save two different Sqlite files via email "Open in" option, I tried using UIAlertView to create to different save file paths but it only seems to work with one way
- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName]; [dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
}
Both file have specific file names so was wonder if I could use "if equal to string" & use an if statement after I have synchronised NSUserDefaults to give two file path save options
Thanks for any help in advance
This was my UIALertView try
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"What type of data do you want to import?"
message:#"Choose data type"
delegate:self
cancelButtonTitle:#"Import RM Name Data"
otherButtonTitles:#"Import Store Visit Data", nil];
NSInteger *buttonIndex = NULL;
NSLog(#"Button Index =%ld",(long)buttonIndex);
if (buttonIndex == 0)
{
}
else if (buttonIndex == 1)
{
databaseExportName = #"export.sql";
NSArray *pathssqlite3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathssqliteDir2 = [pathssqlite3 objectAtIndex:0];
filePathsqlite3 = [pathssqliteDir2 stringByAppendingPathComponent:databaseExportName];
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSMutableData *dbimport = [[NSMutableData alloc] initWithContentsOfURL:urlx];
NSError *writeError = nil;
[dbimport writeToFile:filePathsqlite3 atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
} } [alertdata show];
Still trying to resolve, was hoping this would work, but still cannot crack it
`- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
if([[urlx absoluteString] isEqualToString:#"svrStoreData2.sql"])
{
NSLog(#"If statement called");
//
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName];
[dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
//
else {
databaseExportName = #"export.sql";
NSString *documentsPathy = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathy = [documentsPathy stringByAppendingPathComponent:databaseExportName];
[dbimport writeToFile:filePathy atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
NSLog(#"If statement Not called");
}
}
}
`

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex(NSInteger)buttonIndex {
if ([alertView tag] == 14)
{
if (buttonIndex == 1)
{
[self reviewSave];
}
}
if ([alertView tag] == 11) {
if (buttonIndex == 1)
{
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];}
}
}
Solved the problem, I had another UIAlert, so by adding Tags sorted it

Related

Stop Activity Indicator while no row in Xcode

I am using the code below to retrieve data from Url via PHP file, the tableview controller will start the Activity Indicator. What I am trying to do is to stop the indicator As soon as there are no data has been loaded to the tableview.
Her is the code;
NSString *urlString = [NSString stringWithFormat:#"http:/MyWebSite/ChoseMyLike.php?userName=%#", myString];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!data) {
NSLog(#"connection error: %#", error);
return;
}
NSError *parseError;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
if (!json) {
NSLog(#"JSON Parsing error: %#", parseError);
NSLog(#"data = %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return;
}
NSMutableArray *results = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++) {
NSString *cQasidaName = json[i][#"qasidaName"];
NSString *cQasidaShaerName = json[i][#"qasidaShaerName"];
NSString *cQasidaBody = json[i][#"qasidaBody"];
NSString *cQasidaDate = json[i][#"myDate"];
NSString *cQasidaTime = json[i][#"myTime"];
NSString *cQasidaRate = json[i][#"myRate"];
NSString *cQasidaId = json[i][#"qasidaId"];
NSString *cQasidaUserName = json[i][#"userName"];
NSString *cTheUserId = json[i][#"theUserId"];
NSString *cTheUserNameArabic = json[i][#"userNameArabic"];
[results addObject:[[ListOfObjects alloc] initWithQasidaName: (NSString *) cQasidaName andQasidaShaerName: (NSString *) cQasidaShaerName andQasidaBody: (NSString *) cQasidaBody andQasidaDate: (NSString *) cQasidaDate andQasidaTime: (NSString *) cQasidaTime andQasidaRate: (NSString *)cQasidaRate andQasidaId:cQasidaId andQasidaUserName:cQasidaUserName andTheUserId:cTheUserId andTheUserNameArabic:cTheUserNameArabic]];
}
dispatch_async(dispatch_get_main_queue(), ^{
self.listArray = results;
[self.tableView reloadData];
[spinner stopAnimating];
});
}];
[task resume];
}
At the moment the indicator is not stopping. What do I need to do?
Thanks
Simply call [spinner stopAnimating]; for all return paths:
if (!data) {
NSLog(#"connection error: %#", error);
[spinner stopAnimating];
return;
}
and
if (!json) {
NSLog(#"JSON Parsing error: %#", parseError);
NSLog(#"data = %#", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
[spinner stopAnimating];
return;
}
Note: it's much easier to have a single return statement and then you can always call [spinner stopAnimating]; at the end of the method... consider restructuring your code.

iOS: Zombie Messaged when accessing NSUserDefaults

While profiling the app for Zombies, I get the error below:
Stack:
Code:
When the app is launched, we access several NSUserDefaults properties using similar code as below. Sometimes the app crashes on different methods that are trying to access the defaults.
+(NSString*)getSettingsFileName{
prefs = [NSUserDefaults standardUserDefaults];
return [prefs objectForKey:#"SettingsFileName"]; // EXC_BAD_ACCES (code=1, address=0x8178b6ed)
}
I tried synching NSUserDefaults before accessing it, but I get the same behavior.
Any tips on how to resolve this would be greatly appreciated!
EDIT
+(void)readSettingsDataAndUpdateIncludeDomain:(BOOL)updateDomain MBMHost:(BOOL)updateMBMHost
{
//Read from Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *settingsFileName = [documentsDirectory stringByAppendingPathComponent:SETTINGS_FILE];
NSDictionary *settingsDic = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath:settingsFileName];
if(fileExists) {
settingsDic = [NSDictionary dictionaryWithContentsOfFile:settingsFileName];
} else {
NSError *error = nil;
NSString *settingsBundleFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:SETTINGS_FILE];
BOOL success = [fileManager copyItemAtPath:settingsBundleFilePath toPath:settingsFileName error:&error];
if(success)
settingsDic = [NSDictionary dictionaryWithContentsOfFile:settingsFileName];
}
prefs = [NSUserDefaults standardUserDefaults];
if(!fileExists)
{
//subscription
[prefs setBool:YES forKey:#"Resubscribe"];
}
[prefs setObject:[settingsDic objectForKey:#"ADDRNAME"] forKey:#"ADDRNAME"];
if( updateDomain )
{
[prefs setObject:[settingsDic objectForKey:#"Domain"] forKey:#"Domain"];
}
[prefs setBool:[[settingsDic objectForKey:#"Https"] boolValue] forKey:#"Https"];
if( updateMBMHost )
{
[prefs setObject:[settingsDic objectForKey:#"Host"] forKey:#"Host"];
}
[prefs setObject:[settingsDic objectForKey:#"ServerNode"] forKey:#"ServerNode"];
[prefs removeObjectForKey:#"ULVersion"];
[prefs setObject:[settingsDic objectForKey:#"ULVersion"] forKey:#"ULVersion"];
forKey:#"ULDownloadOnly"];
[prefs setObject:[settingsDic objectForKey:#"AgentName"] forKey:#"AgentName"];
if ([[Settings getSettingsFileName] length] < 1) //This is the Line where it usually crashes"
[prefs setObject:[settingsDic objectForKey:#"SettingsFileName"] forKey:#"SettingsFileName"];
[prefs setObject:[settingsDic objectForKey:#"ScannerType"] forKey:#"ScannerType"];
NSString *supportEmailAddress = [settingsDic objectForKey:#"SupportEmailAddress"];
if( supportEmailAddress == nil )
{
supportEmailAddress = SUPPORT_EMAIL_ADDRESS;
}
[prefs setObject:supportEmailAddress forKey:#"SupportEmailAddress"];
//Don't set SyncCalContactsMode from plist since this will overide the user's selection
if([[settingsDic objectForKey:#"Instance"] length] > 1)
[prefs setObject:[settingsDic objectForKey:#"Instance"] forKey:#"Instance"];
else if ([[Settings getInstance] length] < 1)
[prefs setObject:#"Company" forKey:#"Instance"];
NSString *info = [NSString stringWithFormat:#"ULVersion = %#, ULDownloadOnly = %# ", ([Settings getULVersion]==nil)?#"Version1":[Settings getULVersion], [Settings getULDownloadOnly]?#"YES":#"NO"];
[DebugLog writeDebugData:info];
}

Search Files/Folder inside files of google drive of xcode

I am trying to make google drive file managing app in iOS. I am stuck because I want to search all files using any keyword and it should be display files and folder.Get all files and folder using this code.But if you search somthing, search only current file. Can you suggest me how to get subfiles and folder because it is display only single level not others.
-(void)getGDriveFilesAndFolders
{
GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
if ([self.strPath length] == 0)
{
query.q = #"'root' in parents";
}else{
NSString *queryString = [NSString stringWithFormat:#"'%#' in parents",self.strPath];
query.q=queryString;
}
[GoogleDriveViewController.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,GTLDriveFileList *files,NSError *error)
{
if (error == nil)
{
[marrFiles removeAllObjects];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
for(int i = 0; i < [files items].count; i++)
{
GTLDriveFile *driveFile = (GTLDriveFile*)[files itemAtIndex:i];
if([driveFile.mimeType isEqualToString:#"application/vnd.google-apps.folder"])
{
if([driveFile.explicitlyTrashed intValue]!=1)
{
NSString *fileName = driveFile.title;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:fileName forKey:[NSString stringWithFormat:#"Folder"]];
[dict setValue:driveFile.identifier forKey:#"objectId"];
[marrFiles addObject:dict];
}
}
else{
if([driveFile.explicitlyTrashed intValue] != 1)
{
NSString *fileName = driveFile.title;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:fileName forKey:[NSString stringWithFormat:#"File"]];
long long int sizeData = [driveFile.fileSize intValue];
NSString *stringSize = [FileSizeClass stringSizeForFileWithBytes:[NSNumber numberWithLongLong:sizeData]];
GTLDateTime *modificationDate = (GTLDateTime*)driveFile.modifiedDate;
NSDate *date = [modificationDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
dateString = [dateString createdTimeString];
NSString *stringInfo = [NSString stringWithFormat:#"%# %#",stringSize,dateString];
[dict setValue:stringInfo forKey:[NSString stringWithFormat:#"Size"]];
[dict setValue:driveFile.identifier forKey:#"objectId"];
[dict setValue:driveFile.downloadUrl forKey:#"downloadUrl"];
[dict setValue:driveFile.fileSize forKey:#"FileSize"];
if(driveFile.webContentLink)
{
[dict setValue:driveFile.webContentLink forKey:#"webContentLink"];
}
[marrFiles addObject:dict];
}
}
}
[tblGoogleDrive reloadData];
} else {
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Message",nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
Using a search query like 'folder id' in parents only searches that folder's direct children, not within sub-folders. There is no built-in way to search sub-folders, but you may be able to create a compound query where you search through each sub-folder explicitly, like 'folder' in parents or 'sub-folder1' in parents ...

how could i integrate via me social site into iphone app

hi i want to integrate Via Me social site into my iphone app,i googled but didn't find any samples.
The basic process is as follows:
Create a custom URL scheme for your app. Via Me will use this after the user has been authenticated, to return to your app. In my example, I created one called "robviame://"
Register your app at http://via.me/developers. This will give you a client id and a client secret:
When you want to authenticate the user, you call:
NSString *redirectUri = [[self redirectURI] stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"https://api.via.me/oauth/authorize/?client_id=%#&redirect_uri=%#&response_type=code", kClientID, redirectUri];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
What that will do is fire up your web browser and give the user a chance to log on and grant permissions to your app. When user finishes that process, because you've defined your custom URL scheme, it will call the following method in your app delegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// do whatever you want here to parse the code provided back to the app
}
for example, I'll call a handler for my Via Me response:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
ViaMeManager *viaMeManager = [ViaMeManager sharedManager];
if ([[url host] isEqualToString:viaMeManager.host])
{
[viaMeManager handleViaMeResponse:[self parseQueryString:[url query]]];
return YES;
}
return NO;
}
// convert the query string into a dictionary
- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSArray *queryParameters = [query componentsSeparatedByString:#"&"];
for (NSString *queryParameter in queryParameters) {
NSArray *elements = [queryParameter componentsSeparatedByString:#"="];
NSString *key = [elements[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [elements[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
value = [[value componentsSeparatedByString:#"+"] componentsJoinedByString:#" "];
[dictionary setObject:value forKey:key];
}
return dictionary;
}
That handler might, for example, save the code and then request the access token:
- (void)handleViaMeResponse:(NSDictionary *)parameters
{
self.code = parameters[#"code"];
if (self.code)
{
// save the code
[[NSUserDefaults standardUserDefaults] setValue:self.code forKey:kViaMeUserDefaultKeyCode];
[[NSUserDefaults standardUserDefaults] synchronize];
// now let's authenticate the user and get an access key
[self requestToken];
}
else
{
NSLog(#"%s: parameters = %#", __FUNCTION__, parameters);
NSString *errorCode = parameters[#"error"];
if ([errorCode isEqualToString:#"access_denied"])
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Via Me functions will not be enabled because you did not authorize this app"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
else
{
[[[UIAlertView alloc] initWithTitle:nil
message:#"Unknown Via Me authorization error"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
}
and the code to retrieve the token might look like:
- (void)requestToken
{
NSURL *url = [NSURL URLWithString:#"https://api.via.me/oauth/access_token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSDictionary *paramsDictionary = #{#"client_id" : kClientID,
#"client_secret" : kClientSecret,
#"grant_type" : #"authorization_code",
#"redirect_uri" : [self redirectURI],
#"code" : self.code,
#"response_type" : #"token"
};
NSMutableArray *paramsArray = [NSMutableArray array];
[paramsDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[paramsArray addObject:[NSString stringWithFormat:#"%#=%#", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
}];
NSData *paramsData = [[paramsArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:paramsData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
{
NSLog(#"%s: NSURLConnection error = %#", __FUNCTION__, error);
return;
}
NSError *parseError;
id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError)
{
NSLog(#"%s: NSJSONSerialization error = %#", __FUNCTION__, parseError);
return;
}
self.accessToken = results[#"access_token"];
if (self.accessToken)
{
[[NSUserDefaults standardUserDefaults] setValue:self.accessToken forKey:kViaMeUserDefaultKeyAccessToken];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
Hopefully this will be enough to get you going. This is described in greater detail at the http://via.me/developers page.

How to write Boolean to a plist file

I'm trying to write Boolean to a plist file. My code is:
NSString *filePath = [self dataFilePath];
if (filePath)
{
if (check)
{
NSLog(#"Clear");
[item setObject:[NSNumber numberWithBool:NO] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}else{
NSLog(#"Green");
[item setObject:[NSNumber numberWithBool:YES] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
}else{
NSLog(#"write file was not found");
}
My filePath is:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"CheckMark.plist"];
}
I load my array with:
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
NSLog(#"%#", filePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"CheckMark" ofType:#"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:filePath error:NULL];
}
// load our data from a plist file inside our app bundle
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
NSLog(#"%#", filePath);
NSLog(#"read dataArray");
Every thing works fine, except when I look at the plist file, nothing changes.
I'm writing the plist file to my Documents directory.
Thanks for any help you can give me.
Remember that you need to be using an NSMutableDictionary to be able to set values.

Resources