I am trying to store data to iCloud documents, and read it on another device logged in with the same account.
I can detect iCloud, send data to iCloud and read it back on the same device. I can detect the file is there from the second device, but I get an error 'NSCocoaDomainError - code 260' when I try to read or copy the file.
File Store code:
//CREATE FILE
NSError *error;
NSLog(#"string to write:%#",printString);
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq == nil) {
return;
}
NSURL *cloudURL =[[ubiq URLByAppendingPathComponent:#"Documents" isDirectory:true] URLByAppendingPathComponent:#"CogwindInventory.txt"];
[printString writeToURL:cloudURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
Code to run the query:
self.backups = [[NSMutableArray alloc] init];
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat: #"%K like 'CogwindInventory.txt'", NSMetadataItemFSNameKey];
[self.query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(queryDidFinishGatheringRestore:)
name:NSMetadataQueryDidFinishGatheringNotification
object:self.query];
[self.CloudActivityIndicator startAnimating];
[self.query startQuery];
- (void)queryDidFinishGatheringRestore:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[self loadDataRestore:query];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:query];
self.query = nil;
}
- (void)loadDataRestore:(NSMetadataQuery *)query {
[self.backups removeAllObjects];
for (NSMetadataItem *item in [query results]) {
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
//[self.backups addObject:url.lastPathComponent];
[self.backups addObject: url.filePathURL];
}
if (self.backups.count > 0) {
[self retrievefile];
}
[self OperationComplete];
}
Code to do the read:
- (void) retrievefile
{
NSError *error = nil;
NSURL *ubiq = [self.manager URLForUbiquityContainerIdentifier:nil];
if (ubiq == nil) {
return;
}
NSURL *cloudURL =[self.backups objectAtIndex:0];
NSArray *localtoken = [[NSString stringWithContentsOfURL:cloudURL encoding:NSUTF8StringEncoding error:&error] componentsSeparatedByString:#"\n"];
if ((localtoken == nil) || (error !=nil)) {
[self.CloudStatusText setText: #"Restore operation failed."];
return;
} else {
[self.tokeninventory setPlayerInventoryNames:localtoken];
[self.CloudStatusText setText: #"Restore operation successful. New inventory available"];
}
}
The devices are OS 8.1.1 and OS 8.3. iCloud- Documents is enabled in Xcode, but not iCloudKit.
Any help appreciated. Thank you.
Related
Fetching contact list using CNContactStore and converting complete contact list to VCard, all are coming fine except i am not getting contact image and notes.
NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
});
return;
}
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(#"error = %#", fetchError);
}
for (CNContact *contact in contacts) {
CNContact *contact1 = contact.mutableCopy;
[contactsArray addObject:contact1];
}
NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
NSLog(#"vcardStr = %#",vcardStr);
}];
Contact Profile images from CNContact
if (granted == YES) {
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *Contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error)
{
//error
}
else
{
for (CNContact *contact in Contacts)
{
UIImage *contactProfileImage;
if (contact.imageDataAvailable)
{
UIImage * image = [UIImage imageWithData:contact.imageData];
contactProfileImage = image;
}
else
{
contactProfileImage = [UIImage imageNamed:#"icon.png"];
}
}
Alright,
I'm using Magicalrecord for core data implementation. My app downloads a bunch of info the first time it is loaded. That data is then saved to core data. This is done in the AppDelegate file. But, whenever my app goes to the background or is terminated the data is lost. Here is the didFinishLaunching with options method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(#"My app is starting");
[MagicalRecord setupAutoMigratingCoreDataStack];
//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"AGM_DataSetup"]) {
NSError* jsonError;
NSArray* json;
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus == NotReachable) {
NSLog(#"Offline");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"static" ofType:#"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
json = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
} else {
NSLog(#"Online");
NSData* data = [NSData dataWithContentsOfURL:
aWaterURL];
json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&jsonError];
}
if (!jsonError) {
[MagicalRecord cleanUp];
NSString* folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error])
{
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
if(error)
{
NSLog(#"Delete error: %#", error.description);
}
}
[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:#"Anglers411.sqlite"];
NSLog(#"Initial Data Load");
for (id jsonArea in json) {
// Create an area
Area *area = [Area MR_createEntity];
area.name = [jsonArea objectForKey:#"name"];
area.bulletDescription = [jsonArea objectForKey:#"bulletDescription"];
area.uid = [jsonArea objectForKey:#"id"];
NSArray* jsonLocations = [jsonArea objectForKey:#"locations"];
for (id jsonLocation in jsonLocations) {
// create a location
Location *location = [Location MR_createEntity];
location.uid = [jsonLocation objectForKey:#"id"];
location.name = [jsonLocation objectForKey:#"name"];
location.desc = [jsonLocation objectForKey:#"desc"];
location.directions = [jsonLocation objectForKey:#"directions"];
location.bulletDescription = [jsonLocation objectForKey:#"bulletDescription"];
location.area = area;
NSArray* jsonBugs = [jsonLocation objectForKey:#"bugs"];
for (id jsonBug in jsonBugs) {
Bug *bug = [Bug MR_createEntity];
bug.name = [jsonBug objectForKey:#"name"];
bug.spring = [jsonBug objectForKey:#"spring"];
bug.summer = [jsonBug objectForKey:#"summer"];
bug.fall = [jsonBug objectForKey:#"fall"];
bug.winter = [jsonBug objectForKey:#"winter"];
bug.location = location;
}
}
}
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
if (success) {
NSLog(#"You successfully saved your context.");
} else if (error) {
NSLog(#"Error saving context: %#", error.description);
}
}];
// Set User Default to prevent another preload of data on startup.
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"AGM_DataSetup"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
return YES;
}
Here is the method I use in both applicationDidEnterBackground and ApplicationWillTerminate:
- (void)saveContext {
[MagicalRecord cleanUp];
}
Thanks for any help with this. I have read over every magicalrecord non-persist question on here and haven't found anything that worked.
Take Care,
Ben
Sorry,
After further exploration, I see that it is generally not going to work to set up 2 core data stacks with different names, if you want them to be the same stack... I have corrected this.
I am trying to save a Dictionary of objects to iCloud but when I do it method saveToURL:forSaveOperation: completionHandler: fails. I also tried to override:
- (BOOL)writeContents:(id)contents
andAttributes:(NSDictionary *)additionalFileAttributes
safelyToURL:(NSURL *)url
forSaveOperation:(UIDocumentSaveOperation)saveOperation
error:(NSError **)outError
and of course the super call also returns false. Yet, I would have liked to read the error, but when I try to have the localizedError the compiler reports an error claiming it is not a structure or union.
This is the full piece of code:
-(instancetype)initWithSingleton{
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:
#"Stops"] URLByAppendingPathComponent:kFILENAME];
NSLog(#"file url=%#", ubiquitousPackage);
self=[self initWithFileURL:ubiquitousPackage];
if (self!=nil){
self.favoriteStops=[[NSMutableDictionary alloc] init];
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(#"iCloud access at %#", ubiq);
[self loadDocument];
} else {
NSLog(#"No iCloud access");
}
}
return self;
}
#define kFILENAME #"favorite.dox"
- (void)loadData:(NSMetadataQuery *)query {
if ([query resultCount] == 1) {
NSMetadataItem *item = [query resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSMutableDictionary* dict=[NSKeyedUnarchiver unarchiveObjectWithData:GETReply];
[self setFavoriteStops:dict];
NSLog(#"favorites: %#", favoriteStops);
[self openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"iCloud document opened");
} else {
NSLog(#"failed opening document from iCloud");
}
}];
}
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
_query = nil;
[self loadData:query];
}
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
error:(NSError **)outError
{
if ([contents length] > 0) {
[self setFavoriteStops:[NSKeyedUnarchiver unarchiveObjectWithData:contents]];
}
return YES;
}
- (BOOL)writeContents:(id)contents
andAttributes:(NSDictionary *)additionalFileAttributes
safelyToURL:(NSURL *)url
forSaveOperation:(UIDocumentSaveOperation)saveOperation
error:(NSError **)outError{
//logging
NSString *str;
str= [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
NSLog(#"saving data %#", str);
//logging
NSMutableDictionary *dict=[NSKeyedUnarchiver unarchiveObjectWithData:contents];
NSLog(#"dict=%#", dict);
BOOL success= [super writeContents:contents
andAttributes:additionalFileAttributes
safelyToURL:url
forSaveOperation:saveOperation
error:outError];
NSLog(#"error :%#", outError.localizedDescription) //syntax error
return success;
}
-(void) save{
NSLog(#"file url=%#", [self fileURL]);
[self saveToURL:[self fileURL]
forSaveOperation:UIDocumentSaveForOverwriting
completionHandler:^(BOOL success) {
if (success) { //this returns false
[self openWithCompletionHandler:^(BOOL success) {
NSLog(#"new document saved on iCloud");
}];
} else {
NSLog(#"error in iCloud Saving");
}
}];
}
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
NSLog(#"favorite stops=%# class=%#", self.favoriteStops, [favoriteStops class]);
NSData *archivedData=[NSKeyedArchiver archivedDataWithRootObject:self.favoriteStops];
return archivedData;
}
When I log the url on which to save, that is:
file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~information~inArrivo/Stops/favorite.dox
And when I check the error on the debugger it is:
Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be
completed. (Cocoa error 4.)" UserInfo=0x17bd6cb0
{NSFileNewItemLocationKey=file:///private/var/mobile/Applications/445778BF-86AF-4DE3-9E1B-BAC8F79D14D0/tmp/(A%20Document%20Being%20Saved%20By%20In%20Arrivo%20HD)/favorite.dox,
NSFileOriginalItemLocationKey=file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~information~inArrivo/Stops/favorite.dox,
NSUnderlyingError=0x17bfa860 "The operation couldn’t be completed.
(Cocoa error 4.)",
NSURL=file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~information~inArrivo/Stops/favorite.dox}
How may I fix it or at least know more?
The TSI Apple team answered me and provided me with a working class. Upon checking their version with mine the change seems to boil down to an update to - (void)queryDidFinishGathering:(NSNotification *)notification; by adding:
if (query.results == 0)
{
[self save]; // no favorites file, so create one
}
to make it as follows:
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
//•• added
if (query.results == 0)
{
[self save]; // no favorites file, so create one
}
[self loadData:query];
_query = nil;
}
I got one sample code (iOS) in which I am getting all user's friends (App Id = 377766775651612) but when I using own created app id (app id 707496825976004), I am getting the list of friends who are using my app.
I want all friends
Please help me
Thanks in advance
This is not possible with Graph API version 2.0.
This is not possible with Graph API version 2.0. Any app made after april 2014 will use 2.0. For more details, see this answer:
Get facebook friends with Graph API v.2.0
-(IBAction)permit:(id)sender
{
if ( [facebook isEqualToString:#"yes"])
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle: #"Status!"
message: #"Please Log in first"
delegate: self
cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[Alert show];
}
else
{
[self requestPermissionAndPost];
}
}
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"friends_birthday", nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error && [FBSession.activeSession.permissions indexOfObject:#"publish_actions"] != NSNotFound) {
[self getFriends];
} else if (error) {
if ([FBErrorUtility errorCategoryForError:error] != FBErrorCategoryUserCancelled) {
NSLog(#"error %#",error);
}
}
}];
}
-(void)getFriends
{
[self addMBProgress];
NSString *accsstoken=[[[FBSession activeSession]accessTokenData]accessToken];
NSString *abcd=[NSString stringWithFormat:#"https://graph.facebook.com/me/friends?fields=id,name,picture,birthday,location,email&access_token=%#",accsstoken];
NSURL *url = [NSURL URLWithString:abcd];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL: url];
[request1 setURL:url];
[request1 setHTTPMethod:#"GET"];
NSError *error;
NSURLResponse *response;
urlDataaa = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
if (urlDataaa!=nil)
{
if(NSClassFromString(#"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:urlDataaa
options:0
error:&error];
if(error)
{
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
NSLog(#"results..:%#",results);
[self removeMBProgress];
venues = [results objectForKey:#"data"];
NSLog(#"birthday..%#",venues);
}
}
}
[venues enumerateObjectsUsingBlock:^(NSDictionary *dict,NSUInteger idx,BOOL *stop)
{
NSString *namess = [dict objectForKey:#"name"];
[name addObject:namess];
if ([dict objectForKey:#"birthday"]) {
NSString *birthdayss = [dict objectForKey:#"birthday"];
[birthday addObject:birthdayss];
}
else
{
[birthday addObject:#"No Birthday"];
}
}
];
NSString *query1 = [NSString stringWithFormat:#"DELETE from userdata"];
[[DBManager sharedDatabase]executeQuery:query1];
NSLog(#"query1:%#",query1);
userdata = [[DBManager sharedDatabase]userdata:#"select * from userdata"];
NSLog(#"userdata...%#",userdata);
for (int i=0; i<[name count]; i++)
{
NSString *namesss =[name objectAtIndex:i];
NSString *datesss =[birthday objectAtIndex:i];
NSString *query1 = [NSString stringWithFormat:#"INSERT INTO userdata (name,date) VALUES (\"%#\",\"%#\")",namesss,datesss];
NSLog(#"query1:%#",query1);
[[DBManager sharedDatabase]executeQuery:query1];
}
userdata = [[DBManager sharedDatabase]userdata:#"select * from userdata"];
NSLog(#"userdata...%#",userdata);
[userdata addObjectsFromArray:manualdata];
[tempSearchData removeAllObjects];
[tempSearchData addObjectsFromArray:userdata];
NSLog(#"tempSearchData..%#",tempSearchData);
[friendlist reloadData];
}
From Facebook sdk version 2.0 onwards, they changing the response like that(getting the list of friends who are using my app).I think from a particular date onwards its behave like that.if u register a new app in developer site ,it may behave like that only.
I am trying to implement Core Data in an iOS 7 app (and have successfully done so earlier). However, when I execute the executeFetchRequest method, the app crashes. The most relevant code is added below:
#import "JTHuntingSeasonDB.h"
#implementation JTHuntingSeasonDB
- (id)init {
self = [super init];
if (self) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *documentName = #"JTHuntingDB";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
document = [[UIManagedDocument alloc] initWithFileURL:url];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];
if (fileExists) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"Document opened successfully");
self.allSpecies = [self getSpecies];
self.speciesToday = [self getSpeciesToday];
} else NSLog(#"Failed to open document");
}];
} else {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(#"Document created successfully");
self.allSpecies = [self getSpecies];
self.speciesToday = [self getSpeciesToday];
} else NSLog(#"Failed to create document, path: %#", url);
}];
}
}
return self;
}
#pragma mark - Core Data
- (NSArray *)getSpecies {
if (document.documentState == UIDocumentStateNormal) {
context = document.managedObjectContext;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *country = [defaults stringForKey:#"Country"];
NSString *subregion = [defaults stringForKey:#"Subregion"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"HuntingDates"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES selector:#selector(localizedStandardCompare:)];
request.fetchBatchSize = 150;
request.fetchLimit = 150;
request.sortDescriptors = #[sortDescriptor];
if (subregion.length > 0) {
request.predicate = [NSPredicate predicateWithFormat:#"(country IN %#) AND (subregion IN %#)", country, subregion];
} else {
request.predicate = [NSPredicate predicateWithFormat:#"country IN %#", country];
}
NSError *error;
return [context executeFetchRequest:request error:&error];
}
return nil;
}
The line
return [context executeFetchRequest:request error:&error];
causes the app to crash. This is what I have done and discovered so far:
Simulator: Deleted app and reset content and settings
Xcode: Clean (Build folder)
"context" is not nil
NSLog prints out "Document created/opened successfully"
Only "lldb" is printed in the console when the app crashes
Edit:
After following Wain's advice, I turned exception breakpoint off, got a more descriptive error message saying that the predicate was invalid. Problem solved by replacing IN in the predicate with CONTAINS and also changing the variable "country" so that it did not return nil anymore.
I guess it's your predicates, because IN is a collection operator but you're passing strings (should be array / set).
If you're using strings, you should be using CONTAINS in the predicate.
Assuming the CoreData persistent store lives inside the document, you will want to use a UIManagedDocument