Apple review require my app to remember the folder that user selected last time. But I can not make it under Sandbox. the -setDirectoryURL seems not working under Sandbox.
What should I do? Thank you for your help!
// read string saveFolder from NSUserDefaults
NSOpenPanel * myPanel = [NSOpenPanel openPanel];
[myPanel setTitle:#"Select Output Folder"];
[myPanel setCanChooseDirectories:YES];
[myPanel setCanCreateDirectories:YES];
[myPanel setAllowsMultipleSelection:NO];
[myPanel setCanChooseFiles:NO];
NSLog(#"before openpanel:folder=%#",saveFolder); // <== return normal
[myPanel setDirectoryURL:[NSURL URLWithString:saveFolder.stringValue]];
NSLog(#"readback:folder=%#",[[myPanel URL] path]); // <== return nil here
if ([myPanel runModal] == NSOKButton)
{
//
saveFolder = [[myPanel URL] path]];
// then save the saveFolder string to NSUserDefaults
//
}
it seems we should add and use this entitlement:
com.apple.security.files.bookmarks.app-scope
SAVE THE URL:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSError *error = nil;
NSData *bookmarkData = [[myPanel URL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
if (!error)
{
[defaults setObject:bookmarkData forKey:#"iData"];
[defaults synchronize];
}
READ BACK:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
bookmarkFileURL = nil;
NSData *bookmarkData = [defaults objectForKey:#"iData"];
if (bookmarkData != nil)
{
NSError *error=nil;
bookmarkFileURL = [NSURL URLByResolvingBookmarkData:bookmarkData options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:&error];
if (error != nil) bookmarkFileURL = nil;
}
if (bookmarkFileURL)
{
[bookmarkFileURL startAccessingSecurityScopedResource];
}
//
//
[bookmarkFileURL stopAccessingSecurityScopedResource];
Related
I'm trying to determine the file size on disk of a PHAsset video.
The following code is returning am error "The file “IMG_0188.mov” couldn’t be opened because you don’t have permission to view it."
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
videoURL = [(AVURLAsset*)avAsset URL];
NSNumber *videoDiskFileSize;
NSError *error;
[videoURL getResourceValue:&videoDiskFileSize forKey:NSURLFileSizeKey error:&error];
if(error){
NSLog(#"ERROR %#", error.localizedDescription);
}
NSLog(#"size is %f",[videoDiskFileSize floatValue]/(1024.0*1024.0));
}];
Here's the correct way to do it.
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetHighestQuality resultHandler:^(AVAssetExportSession *exportSession, NSDictionary *info) {
CMTime videoDuration = CMTimeMultiplyByFloat64(exportSession.asset.duration, 1);
exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);
NSLog(#"Byyte size = %lld", exportSession.estimatedOutputFileLength);
videoSize = exportSession.estimatedOutputFileLength;
}];
I'm doing and App in IOS and I want to add a Button that when people clik it it automatically add the contact (name, number and Picture) in the phone contact list
the contact name is Clinica Lo Curro and phone No. is 6003667800
Someone can please help me with the code please?
regards,
Eugenio Durán
Add AddressBook.framework and AddressBookUI.framework from Build Phase,Link Binary with Libraries.
And Import AddressBookUI to your header File as displayed below.
#import <AddressBookUI/AddressBookUI.h>
Include delegate ABPeoplePickerNavigationControllerDelegate to header file.
and Call The following method to add Contact.
-(IBAction)addContact:(id)sender
{
ABPeoplePickerNavigationController *peoplePicker=[[ABPeoplePickerNavigationController alloc] init];
ABAddressBookRef addressBook = [peoplePicker addressBook];
// create person record
ABRecordRef person = ABPersonCreate();
// set name and other string values
UIImage *personImage = [UIImage imageNamed:#"cinema.png"];
NSData *dataRef = UIImagePNGRepresentation(personImage);
NSString *firstName=#"AKASH";
NSString *lastName=#"MALHOTRA";
NSString *organization=#"Aua Comp Pvt Ltd.";
NSString *jobTitle=#"iPhone App Developer";
NSString *departMent=#"Mobile Division";
NSString *webURL=#"http://www.google.com";
NSString *personEmail=#"goel.anjan#gmail.com";
NSString *phoneNo=#"9856756445 or 7656876765 or 8976566775";
NSString *personNote=#"I am just a kid";
NSString *addressOne=#"HN-23,Sector-2,Chandigarh";
NSString *addressTwo=#"AL-19,Sector-5,SaltLake";
NSString *cityName=#"Kolkata";
NSString *stateName=#"West Bengal";
NSString *pinCode=#"700091";
NSString *country=#"India";
CFErrorRef cfError=nil;
ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef)organization, NULL);
if (firstName) {
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(firstName) , nil);
}
if (lastName) {
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(lastName) , nil);
}
if (jobTitle) {
ABRecordSetValue(person, kABPersonJobTitleProperty,(__bridge CFTypeRef)(jobTitle), nil);
}
if (departMent) {
ABRecordSetValue(person, kABPersonDepartmentProperty,(__bridge CFTypeRef)(departMent), nil);
}
if (personNote) {
ABRecordSetValue(person, kABPersonNoteProperty, (__bridge CFTypeRef)(personNote), nil);
}
if (dataRef) {
ABPersonSetImageData(person, (__bridge CFDataRef)dataRef,&cfError);
}
if (webURL)
{
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) webURL, kABPersonHomePageLabel, NULL);
ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil);
CFRelease(urlMultiValue);
}
if (personEmail)
{
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) personEmail, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
CFRelease(emailMultiValue);
}
if (phoneNo)
{
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSArray *venuePhoneNumbers = [phoneNo componentsSeparatedByString:#" or "];
for (NSString *venuePhoneNumberString in venuePhoneNumbers)
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) venuePhoneNumberString, kABPersonPhoneMainLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
CFRelease(phoneNumberMultiValue);
}
// add address
ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
if (addressOne)
{
if (addressTwo)
addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:#"%#\n%#", addressOne, addressTwo];
else
addressDictionary[(NSString *) kABPersonAddressStreetKey] = addressOne;
}
if (cityName)
addressDictionary[(NSString *)kABPersonAddressCityKey] = cityName;
if (stateName)
addressDictionary[(NSString *)kABPersonAddressStateKey] = stateName;
if (pinCode)
addressDictionary[(NSString *)kABPersonAddressZIPKey] = pinCode;
if (country)
addressDictionary[(NSString *)kABPersonAddressCountryKey] = country;
ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL);
CFRelease(multiAddress);
//Add person Object to addressbook Object.
ABAddressBookAddRecord(addressBook, person, &cfError);
if (ABAddressBookSave(addressBook, nil)) {
NSLog(#"\nPerson Saved successfuly");
} else {
NSLog(#"\n Error Saving person to AddressBook");
}
}
Is it possible to save video and add it to custom ALAsset, captured from UIImagePicker in mp4 format? Or I have to save it in .mov and make compression by AVAssetExportSession?
Yes, you can compress video using AVAssetExportSession. Here you can specify video type, quality and output url for compress video.
See below methods:
- (void) saveVideoToLocal:(NSURL *)videoURL {
#try {
NSArray *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [documentsDirectory objectAtIndex:0];
NSString *videoName = [NSString stringWithFormat:#"sampleVideo.mp4"];
NSString *videoPath = [docPath stringByAppendingPathComponent:videoName];
NSURL *outputURL = [NSURL fileURLWithPath:videoPath];
NSLog(#"Loading video");
[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession) {
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
NSLog(#"Compression is done");
}
[self performSelectorOnMainThread:#selector(doneCompressing) withObject:nil waitUntilDone:YES];
}];
}
#catch (NSException *exception) {
NSLog(#"Exception :%#",exception.description);
[self performSelectorOnMainThread:#selector(doneCompressing) withObject:nil waitUntilDone:YES];
}
}
//---------------------------------------------------------------
- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL handler:(void (^)(AVAssetExportSession*))handler {
[[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
handler(exportSession);
}];
}
Here I saved compress video to document directory of application. You can check detail working of this in below sample code:
Sample demo:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
picker.dismiss(animated: true, completion: nil)
guard let mediaType = info[UIImagePickerControllerMediaType] as? String else
{
return
}
if mediaType == "public.movie"
{
if let videoURL = info[UIImagePickerControllerMediaURL] as? URL
{
var videoData:Data!
do {
videoData = try Data(contentsOf: videoURL, options: [Data.ReadingOptions.alwaysMapped])
}
catch
{
print(error.localizedDescription)
return
}
if videoData != nil
{
let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("vid1.mp4")
print("writePath - \(writePath)")
do{
try videoData.write(to: writePath)
}catch{
print("Error - \(error.localizedDescription)")
}
}
}
}
}
We must support some old code that runs using ASIHTTPRequest, but we want the object mapping and core data support provided by RestKit. Does anyone know of any way of "gluing" these two together?
I picture using ASIHTTPRequest for the requests and someone manually forwarding the payload over to RestKit.
Ok, so this wasn't too hard after all. Here is a class I wrote just for this (no disclaimers, it works for us and may be useful for someone else). You can use this as a direct replacement to the standard RKObjectLoader class.
.h file
#import <RestKit/RestKit.h>
#import "ASIFormDataRequest.h"
#interface ASIHTTPObjectLoader : ASIFormDataRequest <RKObjectMapperDelegate> {
RKObjectManager* _objectManager;
RKObjectMapping* _objectMapping;
RKObjectMappingResult* _result;
RKObjectMapping* _serializationMapping;
NSString* _serializationMIMEType;
NSObject* _sourceObject;
NSObject* _targetObject;
}
#property (nonatomic, retain) RKObjectMapping* objectMapping;
#property (nonatomic, readonly) RKObjectManager* objectManager;
#property (nonatomic, readonly) RKObjectMappingResult* result;
#property (nonatomic, retain) RKObjectMapping* serializationMapping;
#property (nonatomic, retain) NSString* serializationMIMEType;
#property (nonatomic, retain) NSObject* sourceObject;
#property (nonatomic, retain) NSObject* targetObject;
- (void) setDelegate:(id<RKObjectLoaderDelegate>)delegate;
+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager: (RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)delegate;
- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)delegate;
- (void)handleResponseError;
#end
.m file
#import "ASIHTTPObjectLoader.h"
#interface ASIFormDataRequest (here)
- (void) reportFailure;
- (void) reportFinished;
#end
#implementation ASIHTTPObjectLoader
#synthesize objectManager = _objectManager;
#synthesize targetObject = _targetObject, objectMapping = _objectMapping;
#synthesize result = _result;
#synthesize serializationMapping = _serializationMapping;
#synthesize serializationMIMEType = _serializationMIMEType;
#synthesize sourceObject = _sourceObject;
- (void) setDelegate:(id<RKObjectLoaderDelegate>)_delegate {
[super setDelegate: _delegate];
}
+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)_delegate {
return [[[self alloc] initWithResourcePath:resourcePath objectManager:objectManager delegate:_delegate] autorelease];
}
- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)_delegate {
self = [super initWithURL: [objectManager.client URLForResourcePath: resourcePath]];
if ( self ) {
self.delegate = _delegate;
_objectManager = objectManager;
}
return self;
}
- (void)dealloc {
// Weak reference
_objectManager = nil;
[_sourceObject release];
_sourceObject = nil;
[_targetObject release];
_targetObject = nil;
[_objectMapping release];
_objectMapping = nil;
[_result release];
_result = nil;
[_serializationMIMEType release];
[_serializationMapping release];
[super dealloc];
}
- (void) reset {
[_result release];
_result = nil;
}
- (void)finalizeLoad:(BOOL)successful error:(NSError*)_error {
//_isLoading = NO;
if (successful) {
//_isLoaded = YES;
if ([self.delegate respondsToSelector:#selector(objectLoaderDidFinishLoading:)]) {
[self.delegate performSelectorOnMainThread:#selector(objectLoaderDidFinishLoading:)
withObject:self waitUntilDone:YES];
}
[super reportFinished];
/*
NSDictionary* userInfo = [NSDictionary dictionaryWithObject:_response
forKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidLoadResponseNotification
object:self
userInfo:userInfo];
*/
} else {
NSDictionary* _userInfo = [NSDictionary dictionaryWithObject:(_error ? _error : (NSError*)[NSNull null])
forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification
object:self
userInfo:_userInfo];
}
}
// Invoked on the main thread. Inform the delegate.
- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary*)resultDictionary {
NSAssert([NSThread isMainThread], #"RKObjectLoaderDelegate callbacks must occur on the main thread");
RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:resultDictionary];
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObjectDictionary:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObjectDictionary:[result asDictionary]];
}
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObjects:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObjects:[result asCollection]];
}
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObject:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObject:[result asObject]];
}
[self finalizeLoad:YES error:nil];
}
#pragma mark - Subclass Hooks
/**
Overloaded by ASIHTTPManagedObjectLoader to serialize/deserialize managed objects
at thread boundaries.
#protected
*/
- (void)processMappingResult:(RKObjectMappingResult*)result {
NSAssert(isSynchronous || ![NSThread isMainThread], #"Mapping result processing should occur on a background thread");
[self performSelectorOnMainThread:#selector(informDelegateOfObjectLoadWithResultDictionary:) withObject:[result asDictionary] waitUntilDone:YES];
}
#pragma mark - Response Object Mapping
- (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvider*)mappingProvider toObject:(id)targetObject error:(NSError**)_error {
NSString* MIMEType = [[self responseHeaders] objectForKey: #"Content-Type"];
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType: MIMEType];
NSAssert1(parser, #"Cannot perform object load without a parser for MIME Type '%#'", MIMEType);
// Check that there is actually content in the response body for mapping. It is possible to get back a 200 response
// with the appropriate MIME Type with no content (such as for a successful PUT or DELETE). Make sure we don't generate an error
// in these cases
id bodyAsString = [self responseString];
if (bodyAsString == nil || [[bodyAsString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
RKLogDebug(#"Mapping attempted on empty response body...");
if (self.targetObject) {
return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionaryWithObject:self.targetObject forKey:#""]];
}
return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]];
}
id parsedData = [parser objectFromString:bodyAsString error:_error];
if (parsedData == nil && _error) {
return nil;
}
// Allow the delegate to manipulate the data
if ([self.delegate respondsToSelector:#selector(objectLoader:willMapData:)]) {
parsedData = [[parsedData mutableCopy] autorelease];
[self.delegate objectLoader: (RKObjectLoader*)self willMapData:&parsedData];
}
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
mapper.targetObject = targetObject;
mapper.delegate = self;
RKObjectMappingResult* result = [mapper performMapping];
// Log any mapping errors
if (mapper.errorCount > 0) {
RKLogError(#"Encountered errors during mapping: %#", [[mapper.errors valueForKey:#"localizedDescription"] componentsJoinedByString:#", "]);
}
// The object mapper will return a nil result if mapping failed
if (nil == result) {
// TODO: Construct a composite error that wraps up all the other errors. Should probably make it performMapping:&error when we have this?
if (_error) *_error = [mapper.errors lastObject];
return nil;
}
return result;
}
- (RKObjectMappingResult*)performMapping:(NSError**)_error {
NSAssert( isSynchronous || ![NSThread isMainThread], #"Mapping should occur on a background thread");
RKObjectMappingProvider* mappingProvider;
if (self.objectMapping) {
NSString* rootKeyPath = self.objectMapping.rootKeyPath ? self.objectMapping.rootKeyPath : #"";
RKLogDebug(#"Found directly configured object mapping, creating temporary mapping provider for keyPath %#", rootKeyPath);
mappingProvider = [[RKObjectMappingProvider new] autorelease];
[mappingProvider setMapping:self.objectMapping forKeyPath:rootKeyPath];
} else {
RKLogDebug(#"No object mapping provider, using mapping provider from parent object manager to perform KVC mapping");
mappingProvider = self.objectManager.mappingProvider;
}
return [self mapResponseWithMappingProvider:mappingProvider toObject:self.targetObject error:_error];
}
- (void)performMappingOnBackgroundThread {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSError* _error = nil;
_result = [[self performMapping:&_error] retain];
NSAssert(_result || _error, #"Expected performMapping to return a mapping result or an error.");
if (self.result) {
[self processMappingResult:self.result];
} else if (_error) {
[self failWithError: _error];
}
[pool drain];
}
- (BOOL)canParseMIMEType:(NSString*)MIMEType {
if ([[RKParserRegistry sharedRegistry] parserForMIMEType: MIMEType]) {
return YES;
}
RKLogWarning(#"Unable to find parser for MIME Type '%#'", MIMEType);
return NO;
}
- (BOOL)isResponseMappable {
if ([self responseStatusCode] == 503) {
[[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self];
}
NSString* MIMEType = [[self responseHeaders] objectForKey: #"Content-Type"];
if ( error ) {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError: error];
[self finalizeLoad:NO error: error];
return NO;
} else if ([self responseStatusCode] == 204) {
// The No Content (204) response will never have a message body or a MIME Type. Invoke the delegate with self
[self informDelegateOfObjectLoadWithResultDictionary:[NSDictionary dictionaryWithObject:self forKey:#""]];
return NO;
} else if (NO == [self canParseMIMEType: MIMEType]) {
// We can't parse the response, it's unmappable regardless of the status code
RKLogWarning(#"Encountered unexpected response with status code: %ld (MIME Type: %#)", (long) [self responseStatusCode], MIMEType);
NSError* _error = [NSError errorWithDomain:RKRestKitErrorDomain code:RKObjectLoaderUnexpectedResponseError userInfo:nil];
if ([self.delegate respondsToSelector:#selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[self.delegate objectLoaderDidLoadUnexpectedResponse: (RKObjectLoader*)self];
} else {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError: _error];
}
// NOTE: We skip didFailLoadWithError: here so that we don't send the delegate
// conflicting messages around unexpected response and failure with error
[self finalizeLoad:NO error:_error];
return NO;
} else if (([self responseStatusCode] >= 400 && [self responseStatusCode] < 500) ||
([self responseStatusCode] >= 500 && [self responseStatusCode] < 600) ) {
// This is an error and we can map the MIME Type of the response
[self handleResponseError];
return NO;
}
return YES;
}
- (void)handleResponseError {
// Since we are mapping what we know to be an error response, we don't want to map the result back onto our
// target object
NSError* _error = nil;
RKObjectMappingResult* result = [self mapResponseWithMappingProvider:self.objectManager.mappingProvider toObject:nil error:&_error];
if (result) {
_error = [result asError];
} else {
RKLogError(#"Encountered an error while attempting to map server side errors from payload: %#", [_error localizedDescription]);
}
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError:_error];
[self finalizeLoad:NO error:_error];
}
#pragma mark - RKRequest & RKRequestDelegate methods
- (void) reportFailure {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError:error];
[super reportFailure];
}
- (void)reportFinished {
NSAssert([NSThread isMainThread], #"RKObjectLoaderDelegate callbacks must occur on the main thread");
if ([self isResponseMappable]) {
// Determine if we are synchronous here or not.
if (isSynchronous) {
NSError* _error = nil;
_result = [[self performMapping:&_error] retain];
if (self.result) {
[self processMappingResult:self.result];
} else {
[self performSelectorInBackground:#selector(failWithError:) withObject:_error];
}
[super reportFinished];
} else {
[self performSelectorInBackground:#selector(performMappingOnBackgroundThread) withObject:nil];
}
}
}
I do the following in my unit test code to make sure my object mappings are working
NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:#"application/json", #"X-RESTKIT-CACHED-MIME-TYPE",
#"200", #"X-RESTKIT-CACHED-RESPONSE-CODE",
#"application/json; charset=utf-8", #"Content-Type",
nil];
NSURL *url = [[NSURL alloc] initWithString:#""]; //need a url to create a dummy RKRequest
RKRequest *request = [RKRequest requestWithURL:url];
[url release];
//Create a dummy response with the data payload
RKResponse *response = [[[RKResponse alloc] initWithRequest:request
body:myData //myData is NSData loaded from my file on disk in this case
headers:headers] autorelease];
RKURL *rkURL = [[RKURL alloc] initWithString:#"https://api.twitter.com"];
RKManagedObjectLoader *loader = [[RKManagedObjectLoader alloc] initWithURL:rkURL
mappingProvider:self.objectManager.mappingProvider
objectStore:self.objectManager.objectStore];
loader.delegate = self;
loader.objectMapping = self.objectMapping; //I pass the object mapping to use here.
[loader didFinishLoad:response]; //Given a response and request, Restkit will parse the response and call the usual delegates
You might be able to do somthing similar as well to grab the response data from ASIHTTPRequest and pass it on to RestKit
here is code for my database
SQLiteTutorialAppDelegate.m
$.-(void) readAnimalsFromDatabase {
sqlite3 *database;
animals = [[NSMutableArray alloc] init];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select * from animals";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new animal object with the data from the database
Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];
// Add the animal object to the animals Array
[animals addObject:animal];
[animal release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
and here RootViewController.m
$.- (void)searchBar:(UISearchBar *)SearchBar textDidChange:(NSString *)searchText {
[copyListOfItems removeAllObjects];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
for (NSArray *rowArray in appDelegate.animals)
{
for ( NSString *aName in rowArray )
{
[searchArray addObject:rowArray]; // HERE CRASH
}
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length == 0)
[copyListOfItems addObject:sTemp];
}
[self.tableView reloadData];
}
please help me how to make search bar search database in TableView
http://www.appcoda.com/search-bar-tutorial-ios7/
This gives you an example of how the search bar uses things around it and how it works
I Recently worked on something similar and this website should tell you everything wrong as well as give you an example of how it works