iOS 9 Making Code go Sequentially (Touch ID) - ios

I am a developer using self-taught Objective-C to code for the iPhone. We are using Xcode 7 and iOS 9. I am tasked with creating an app for my company to communicate when someone arrives and leaves an appointment in a schedule made for them (using XML).
We would like to use Touch ID for security so the users don’t have to log in a lot. Security is required because of the confidentiality of the data in the app. I had the application working. Or it looked like it worked, until I clicked on the Cancel option in Touch ID and realized that the Touch ID was providing no security.
I believe this is because the methods that are supposed to run after Touch ID were outside of the LA Context block. I put them outside because I need to return a string value on a successful authorization (an internal employee number retrieved through XML). If I put the methods with the returned NSStrings outside of the LA Context block, the methods run in the wrong order.
How can I make the following 4 methods run in sequential order?
1)requireLogin (Touch ID code here)
2)requestSession
3)readSession
4)checkSession
If the Touch ID fails, methods 2-4 should not run.
I’ve looked at blocks. I’ve looked at GCD. I can’t find any examples on how to deal with this. If someone could point me in the right direction. I would really appreciate it. If I need to include more of the code, please let me know.
Thank you in advance.
- (NSString *)retrieveESN {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
NSString *fullPath = [documentsDirectoryPath stringByAppendingString:#"/session.txt"];
if ([fileManager fileExistsAtPath:fullPath]==YES) {
_finished = false;
NSLog(#"File exists");
[self readSession];
NSLog(#"%#", _sessionDetail);
NSLog(#"Pre Check Session");
NSString *result = [self checkSession:_sessionDetail];
NSLog(#"Post Check Session");
NSLog(#"%#", result);
if ([result isEqualToString:#"Error"]) {
NSLog(#"Error received - going into newFile");
NSString *userESN = [self newFile];
NSLog(#"Error'd returning with result");
NSLog(#"UserESN: %#", userESN);
return userESN;
} else {
NSLog(#"No Error Received");
NSLog(#"Returning result: %#", result);
return result;
}
} else {
_finished = false;
NSLog(#"No file exists, call newFile");
NSString *userESN = [self newFile];
NSLog(#"UserESN: %#", userESN);
return userESN;
}
}
- (NSString *)newFile {
NSLog(#"File does not exist.");
[self requireLogin];
NSLog(#"Out of requireLogin");
[self requestSession];
NSLog(#"Out of requestSession");
[self readSession];
NSLog(#"Out of readSession");
NSString *userESN = [self checkSession:_sessionDetail];
NSLog(#"Into checkSession again newfile");
return userESN;
}
- (void)requireLogin {
LAContext *context = [[LAContext alloc] init];
NSError *error = nil;
NSLog(#"Into requireLogin");
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
// Authenticate User
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:#"You must log in to the app."
reply:^(BOOL success, NSError * _Nullable error) {
if (success) {
_finished = true;
NSLog(#"success");
} else {
switch (error.code) {
case LAErrorAuthenticationFailed:
NSLog(#"Authentication Failed");
break;
case LAErrorUserCancel:
NSLog(#"User pressed Cancel button");
break;
case LAErrorUserFallback:
//Return to go to Enter Password not available screen.
NSLog(#"User pressed Enter Password");
break;
default:
NSLog(#"Touch ID is not configured");
break;
}
NSLog(#"Authentication Fails");
}
}];
} else {
NSLog(#"Phone doesn't support Touch ID.");
}
}
- (void)requestSession {
NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *url = #“https://companyurl.com/session_page”;
NSLog(#"Got to requestSession");
NSMutableString *postText = [[NSMutableString alloc] init];
NSLog(#"%#", idfv);
[postText appendString:idfv];
NSString *postBody = [NSString stringWithString:postText];
XMLPostSecurity *postAction = [[XMLPostSecurity alloc] init];
NSLog(#"Got to PostAction");
_sessionDetail = [postAction sendPostRequestToUrl:url withBody:postBody];
NSLog(#"Session Detail: %#", _sessionDetail);
FileSaving *saver = [[FileSaving alloc] init];
[saver saveSession:self.sessionDetail];
NSLog(#"Saved file.");
}
-(NSString *)readSession {
NSLog(#"In to readSession.");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
NSString *fullPath = [documentsDirectoryPath stringByAppendingString:#"/session.txt"];
while ([fileManager fileExistsAtPath:fullPath]==NO);
NSFileManager *fileManagerTwo;
NSData *dataBuffer;
fileManagerTwo = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:#"/session.txt"];
NSLog(#"Got Path");
dataBuffer = [fileManagerTwo contentsAtPath:filePath];
NSLog(#"databuffer created");
_sessionDetail = [[NSString alloc] initWithData:dataBuffer encoding:(NSASCIIStringEncoding)];
NSLog(#"File read: %#", _sessionDetail);
return _sessionDetail;
}
-(NSString *)checkSession:(NSString *)sessionFound {
NSLog(#"Into checkSession");
NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
#"ollie/", NSHTTPCookieDomain,
#"\\", NSHTTPCookiePath,
#"cookieName", NSHTTPCookieName,
sessionFound, NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray *cookieArray = [NSArray arrayWithObject:cookie];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
NSMutableString *url = [[NSMutableString alloc] initWithString:#“https://companyurl.com/xmlfile.php”];
NSLog(#"%#", url);
NSURL *urlNew = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlNew];
[request setHTTPMethod:#"GET"];
[request setAllHTTPHeaderFields:headers];
self.parseData = NULL;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"dataTaskWithRequest HTTP status code: %ld", (long)statusCode);
if (statusCode == 401) {
// Insert process for thumbprint and session cookie pull
NSLog(#"401 Error received");
NSFileManager *fileManagerThree = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sessionPath = [documentsPath stringByAppendingPathComponent:#"session.txt"];
NSError *error;
BOOL success = [fileManagerThree removeItemAtPath:sessionPath error:&error];
if (success) {
NSLog(#"File deleted - check session.");
} else {
NSLog(#"File could not be deleted.");
}
} else {
NSLog(#"I got something other than 200 or 401");
return;
}
}
}
self.parseData = data;
}];
[task resume];
while ( self.parseData == NULL );
ParseTypeXML *myParser = [[ParseTypeXML alloc] initWithData:self.parseData];
if ([myParser.esn count] == 0) {
return #"Error";
} else {
return myParser.esn[0];
}
}

Related

How to unzip file?

I use SSZipArchive. After downloading file I want to unzip archive and show image. But code doesn’t work. How to fix it?
download file
-(IBAction) downloadButton:(id)sender
{
if (_HighScore == 2) {
_url1 =[NSURL URLWithString:#"link2.zip"];
_downloadTask1 = [_session downloadTaskWithURL:_url1];
[_downloadTask1 resume];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
if (downloadTask == _downloadTask1) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSURL *documentsFolder = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *newLocation = [NSURL URLWithString:[NSString stringWithFormat:#"file://%#/2.zip", documentsFolder]];
NSError *error;
[fileManager copyItemAtURL:location toURL:newLocation error:&error];
NSLog(#"file%#", newLocation.absoluteString);
}
unzip file
_documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
_zipPath1 = [_documentsDirectory1 stringByAppendingPathComponent:#"2.zip"];
_destinationPath1 = [_documentsDirectory1 stringByAppendingPathComponent:#"file://%#/2.zip"];
_fileExists1 = [[NSFileManager defaultManager] fileExistsAtPath:_zipPath1 isDirectory:false];
if( [SSZipArchive unzipFileAtPath:_zipPath1 toDestination:_destinationPath1] != NO ) {
NSLog(#"Dilip Success");
}else{
NSLog(#"Dilip Error");
}
UPD
-(IBAction) downloadButton:(id)sender
{
if (_HighScore == 2) {
_url1 =[NSURL URLWithString:#"link2.zip"];
_downloadTask1 = [_session downloadTaskWithURL:_url1];
[_downloadTask1 resume];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
if (downloadTask == _downloadTask1) {
_documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
_zipPath1 = [_documentsDirectory1 stringByAppendingPathComponent:#"2.zip"];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (downloadTask == _downloadTask1) { NSData *urlData1 = [NSData dataWithContentsOfURL:_url1]; [urlData1 writeToFile:_zipPath1 atomically:YES];}
});
}
The problem is in saving zip file in DocumentDirectory, _filePath1 is contain the destination folder for unzip, instead of that you need to use filePath that contain zip file name along with path, so use that like this.
[urlData1 writeToFile:filePath atomically:YES];
Also it is batter if you use writeToFile:options:error: method so that you can know it is successfully writing Data or not.
NSError *error = nil;
[self.responseData writeToFile:zipPath options:0 error:&error];
Edit:
You are probably messing with something, so change your code from downloading to saving and unzipping like this.
-(IBAction) downloadButton:(id)sender
{
if (_HighScore == 2) {
_url1 =[NSURL URLWithString:#"link2.zip"];
_downloadTask1 = [session dataTaskWithURL:[NSURL URLWithString:#""] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Saved in NSDocumentDirectory
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *zipPath = [path stringByAppendingPathComponent:#"2.zip"];
[self.responseData writeToFile:zipPath options:0 error:&error];
//UNZip
NSString *zipPath1 = [path stringByAppendingPathComponent:#"2.zip"];
NSString *destinationPath = [NSString stringWithFormat:#"%#",path];
[SSZipArchive unzipFileAtPath:zipPath1 toDestination:destinationPath];
//Now access the content of zip
}];
[_downloadTask1 resume];
}
}
try like this , its work for me
[SSZipArchive unzipFileAtPath:filePath toDestination:outputPath delegate:self];
after completion of unarchive the following method will call
#pragma mark - Unzipp Delegate
- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo: (unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath {
//write code here after unarchive zip file
}

How to Access local JSON file response in NSDictionary for showing in UITableView?

Basically I got response from server side and then i saved it in local file.Actually I fetched the response from server side and then saved into documents directory ,and now trying to fetch but it comes in NSString only ,i unable to get in NSDictionary....Here is following code
- (IBAction)loginButtonPressed:(id)sender
{
NSString *URLString = #"http://localhost/rest/login";
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"username": userNameTxtField.text, #"password": pwdTextField.text};
NSLog(#"Parameters:\n%#",params);
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
{
NSLog(#"Successfully Login ....: %#", responseObject);
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [NSString stringWithFormat:#"%#/sample.json", documents];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
NSError *writeError = nil;
NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];
if ((bytesWritten = 0))
{
NSLog(#"Error writing JSON Data");
}
else{
NSLog(#"Sucessfuly saved data...");
}
[stream close];
NSLog(#"path is :%#",path);
} failure:^(NSURLSessionDataTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
- (IBAction)fetch:(id)sender
{
NSError *deserializingError;
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"vaues are:%#",dict);
}
Your response object should be a type of NSDictionary. Therefore you can use its writeToFileAtPath method to save it to your documents directory.
When recreating the dictionary, you can use the NSDictionary's alloc and initWithContentsOfFile method to directly create a NSDictionary instance.
There are tons of posts on how to do that if you do a little Google search!
Try this!! It's working fine.
NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
[testStore setObject:#"vignesh" forKey:#"username"];
[testStore setObject:#"password" forKey:#"password"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(#"Got an error: %#", error);
jsonString = #"";
}
[self writeStringToFile:jsonString];
NSLog(#"Your JSON String is %#", [self readStringFromFile]);
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// Write to file
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// read from file
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;
#implementation DatabaseOperation
#synthesize databasePath;
+(DatabaseOperation*)sharedInstances{
if(!_sharedInstances){
_sharedInstances =[[super allocWithZone:nil]init];
}
return _sharedInstances;
}
+(id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstances];
}
-(id)init{
NSLog(#"Only first time Instances using Singleton:");
self =[super init];
if(self){
[self CreateDbpath];
}
return self;
}
-(BOOL)CreateDbpath{
NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];
self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:#"Mindset.sqlite"]];
NSFileManager *flg = [NSFileManager defaultManager];
BOOL isSuccess = false;
if([flg fileExistsAtPath:databasePath]==NO){
char *ermsgss = nil;
char const *dbpathss =[self.databasePath UTF8String];
if(sqlite3_open(dbpathss, &studs)==SQLITE_OK){
char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";
if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK){
NSLog(#"Failed to create table:");
}
else{
NSLog(#"Successfully to create table:");
}
}
sqlite3_close(studs);
}
return isSuccess;
}
-(void)insertDatabaseValue:(DataManagers *)getInserted{
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery=[[NSString alloc]initWithFormat:#"insert into emp values(?,?,?)"];
const char *_sqlQuery=[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);
NSData *jpegData =[[NSData alloc]init];
NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);
UIImage *imgesData =[UIImage imageWithData:imgeData];
CGRect rect = CGRectMake(0, 0, 185, 150);
UIGraphicsBeginImageContext(rect.size);
[imgesData drawInRect:rect];
UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
;
UIGraphicsEndImageContext();
jpegData = UIImageJPEGRepresentation(img, 0.01f);
sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);
if(sqlite3_step(ermsg)==SQLITE_DONE){
NSLog(#"Successfully inserted into db:");
}
else {
NSLog(#"Error %s",sqlite3_errmsg(studs));
}
}
sqlite3_close(studs);
sqlite3_finalize(ermsg);
}
}
-(NSMutableArray*)getAllData {
NSMutableArray *array =[[NSMutableArray alloc]init];
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery =[[NSString alloc]initWithFormat:#"select * from emp"];
const char *_sqlQuery =[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
while (sqlite3_step(ermsg)==SQLITE_ROW) {
DataManagers *mgr =[[DataManagers alloc]init];
NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;
mgr.userName = _Firstname;
NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;
mgr.cityName = lastName;
int imgBytes = sqlite3_column_bytes(ermsg, 2);
UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];
mgr.profileImg = img;
[array addObject:mgr];
}
}
}
return array;
}

ios - transfer In App Purchase downloaded file to Document folder

I successfully test my in app purchase function and downloaded the content. However I am not sure of an right way to transfer it to Document folder. I tested with the code:
-(void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray *)downloads
{
for (SKDownload *download in downloads)
{
switch (download.downloadState) {
case SKDownloadStateActive:
NSLog(#"Download progress = %f",
download.progress);
NSLog(#"Download time = %f",
download.timeRemaining);
break;
case SKDownloadStateFinished:
[self downloadFromURL:download.contentURL];///<--This is the function.
break;
}
}
}
-(void)downloadFromURL: (NSURL *) temporaryURL {
NSString *folderName = [[temporaryURL path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:folderName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
NSData *downloadData = [[NSData alloc] initWithContentsOfURL:temporaryURL];
[downloadData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#"Error in writing file %#' : \n %# ", filePath , writeError);
return;
}
NSLog(#"File successfully downloaded. Url is %#",fileURL.absoluteString);
//myFileURL = fileURL;
NSFileManager *filemgr;
NSArray *filelist;
int count;
int i;
filemgr =[NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:folder error:NULL];
count = [filelist count];
NSLog(#"file count %i",count);
for (i = 0; i < count; i++)
NSLog(#"%#", filelist[i]);
}
I get a #"File successfully downloaded. Url is %#" from the code above but NSLog(#"%#", filelist[i]); give me no content. What else is missing here? I found out about this link
but not sure how to incorporate into my code. Any pointer will be good.
Let's check:
-(void)downloadFromURL: (NSURL *) temporaryURL {
// at this time, file is downloaded successfully???
// I think you should check here
NSURL * temporaryURL;
NSFileManager *fm = [NSFileManager defaultManager];
BOOL existed = [fm fileExistsAtPath:temporaryURL.path];
if(existed) // file is existed
else // file is not existed == maybe download fails
}

addSkipBackupAttributeToItemAtURL not working with iOS7

My iOS application just got rejected because the application is storing data on Documents so it is backed up by iCloud, this is not allowed since the data is downloaded from a server.
But even though I'm using addSkipBackupAttributeToItemAtURL it still shows up as a backup to iCloud.Here the code which i have used
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
[self HidePreLoader];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"_paths--->%#",paths);
NSString *path = [paths objectAtIndex:0];
NSLog(#"_path---->%#",path);
NSString *dataPath = [path stringByAppendingPathComponent:#"/MyFolder"];
NSLog(#"_dataPath---->%#",dataPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *zipPath = [dataPath stringByAppendingPathComponent:downfilename];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
[self HidePreLoader];
ZipArchive *za = [[ZipArchive alloc] init];
if ([za UnzipOpenFile: zipPath]) {
BOOL ret = [za UnzipFileTo: dataPath overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
NSLog(#"folderPath--->%#",folderPath);
//Here i have used the use code
NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
[guidesURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:NULL];
//The following code also doesnt work
//NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
//[self addSkipBackupAttributeToItemAtURL:guidesURL];
[self HidePreLoader];
NSString *path = nil;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-tablet.html"];
}
else
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-phone.html"];
}
NSLog(#"path--->%#",path);
dispatch_async(dispatch_get_main_queue(), ^{
appDel.currentReadingPlanWithPath = path;
appDel.moduleDownloaded = YES;
[appDel SetCurrentDownloadPath];
NSLog(#"file download success");
[progview setHidden:YES];
[progval setHidden:YES];
[self HidePreLoader];
downloadView.userInteractionEnabled=YES;
[self SetModuleDownloaded:#"true"];
[self ShowAlert:#"Download" message:#"Success"];
[self HidePreLoader];
});
[self HidePreLoader];
}
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
});
AddSkipBackupAttributeToItemAtURL method
-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
return success;
}
When i try the above code.Still the iCloud shows the application in iOS7.Please help me to solve this issue.
Please check iOS version before using "addSkipBackupAttributeToItemAtURL" function.
Also follow this URL :
https://developer.apple.com/library/ios/qa/qa1719/_index.html
and this URL
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTuning/PerformanceTuning.html#//apple_ref/doc/uid/TP40007072-CH8-SW9

create folder inside nsoperation failed

I use this method inside an NSOperation for check and create a folder:
- (void) checkAndCreateFolderWithPath:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathDaControllare = [[self getLibraryPath] stringByAppendingPathComponent:path];
NSError *error = nil;
BOOL isDir;
BOOL exists = [fileManager fileExistsAtPath:pathDaControllare isDirectory:&isDir];
if (exists) {
if (isDir) {
}
}
else {
[fileManager createDirectoryAtPath:pathDaControllare
withIntermediateDirectories:YES
attributes:nil
error:&error];
NSLog(#"%#",error);
}
}
Using NSOperation I get this error:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed.
if I don't use NSOperation all work perfectly, this is the nsoperation
- (void) main {
NSString *filePath = [fileDict objectForKey:#"url"];
NSString *urlStr = [NSString stringWithFormat:#"http://www.allmyapp.net/wp-content/iFormulario_Update/%#",filePath];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data) {
NSString *folderPath = [filePath stringByReplacingOccurrencesOfString:[filePath lastPathComponent] withString:#""];
[self checkAndCreateFolderWithPath:folderPath];
NSString *pathFile = [[self getLibraryPath] stringByAppendingString:filePath];
[data writeToFile:pathFile atomically:YES];
[self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:pathFile]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"endFile" object:nil];
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
isExecuting = NO;
isFinished = YES;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
}];
}
And this the method for create the queue:
for (NSDictionary *dict in fileDaScaricare) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithDictionary:dict];
[self.operationQueue addOperation:downloadOperation];
}
You can try something like this:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/MyFolder"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *docFolderPath = [stringPath stringByAppendingString:[NSString stringWithFormat: #"/%#", self.downloadedFilename]];
[data writeToFile:docFolderPath atomically:YES];
It worked for me, and I am able to download a file in MyFolder. Hope it works for you. Please let me know if it works.

Resources