Search code examples
objective-ccocoansarraygdata-api

Unable to write NSArray to file


I am using google contact data objective c APIs for fetching contacts. I got contacts array from google server now i want to write contact to file. i am using writeToFile:atomically: method for writing array to file but This method is not working for me since i feel that output array from gdata API not contain property list objects. Please suggest any alternate solution.

-(void)fetchData{
    GDataServiceGoogleContact *service=[[GDataServiceGoogleContact alloc] init];
    [service setShouldCacheResponseData:YES];
    [service setServiceShouldFollowNextLinks:YES];
   [service setUserCredentialsWithUsername:[mUsername stringValue] password:[mPassword stringValue]];

    // GENERATING THE URL
    NSURL *feedURL=[GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
    GDataQuery *contQuery=[GDataQueryContact contactQueryWithFeedURL:feedURL];
    [contQuery setShouldShowDeleted:YES];
    [contQuery setMaxResults:2000];
    GDataServiceTicket *ticket=[service fetchFeedWithQuery:contQuery delegate:self didFinishSelector:@selector(hasFetchedContacts:feed:error:)];    
}


-(void) hasFetchedContacts:(GDataServiceTicket*) ticket  feed:(GDataFeedContact*) contacts error:(NSError*) err
{
    NSArray *contactList=[contacts entries];
    NSLog(@"%d",[list writeToFile:@"/Users/subhranil/Desktop/contactList" atomically:NO]);  

}

Solution

  • You can use byte array for this purpose and NSData for writing to file.
    For saving:

    NSData *data=[[NSData alloc] initWithBytes:[contacts entries] length:total];
    [data writeToFile:@"path" atomically:YES];
    

    total= The total size of the array in bytes

    For retrieving:

       NSData *newdata = [NSData dataWithContentsOfFile:@"path"];
       NSUInteger len = [newdata length];
       Byte *byteData = (Byte*)malloc(len);
       memcpy(byteData, [newdata bytes], len);
    

    byteData will now contain an array of GDataEntryContact objects and you can use them accordingly.