IOS Share Extension NSMutableArray addObject Unrecognized selector sent to instance - ios

After clicking post to the share dialog, the Host App(e.g. Safari) hangs up if arrSites variable is currently not empty. I can only store 1 object inside my arrSites variable. How can I addObject to my NSMutableArray variable?
Below is my implemented code and it generates an error in [arrSites addObject:dictSite] line.
- (void)didSelectPost
{
inputItem = self.extensionContext.inputItems.firstObject;
NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];
if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
{
NSLog(#"++++++++++ Attachment is a URL");
[urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
{
if (error)
{
NSLog(#"Error occured");
}
else
{
NSMutableArray *arrSites;
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
}else{
arrSites = [[NSMutableArray alloc] init];
}
NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, #"Text", url.absoluteString, #"URL",nil];
[arrSites addObject:dictSite];
[sharedUserDefaults setObject:arrSites forKey:#"SharedExtension"];
[sharedUserDefaults synchronize];
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Success"
message:#"V7 Posted Successfully."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[UIView animateWithDuration:0.20 animations:^
{
self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
}
completion:^(BOOL finished)
{
[self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
}];
}];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}

Without memory allocation you can't add the object to array, use like
// allocate the memory of array in before
NSMutableArray *arrSites = [[NSMutableArray alloc] init];
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
[arrSites addObjectsFromArray:[sharedUserDefaults objectForKey:#"SharedExtension"]];
}
[arrSites addObject:dictSite];

Most likely the source of the problem is that
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
creates immutable object (NSArray instead of NSMutableArray). You can fix this issue using
arrSites = [[sharedUserDefaults objectForKey:#"SharedExtension"] mutableCopy];
instead.

Related

Async call causing EXC_BAD_INSTRUCTION crash

The app I'm working on is using a function that is working fine but blocks the main thread. I am attempting to add a loading spinner using SVProgressHUD and that requires I call my function asynchronously in order to display the spinner. As soon as I call the function asynchronously however the app crashes with EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0 The only change I have made to the function is to invoke the popViewControllerAnimated lines on the main thread. Why is running this code on a new thread causing it to crash and how can I fix it?
Calling code:
-(void) _doSaveDataPoint {
[SVProgressHUD show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self _saveDataPoint];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
});
}
_saveDataPoint function. popViewController called on main thread near the end of this code:
-(void) _saveDataPoint {
NSString *errorMsg = nil;
if ([[myLegend type] isEqualToString:#"PIN"]) {
if ([myNodes count]==0) {
errorMsg = #"Please make sure you have added one point on to the map to continue.";
}
}
else if ([[myLegend type] isEqualToString:#"POLYGON"]) {
if ([myNodes count]<3) {
errorMsg = #"Please make sure you have at least 3 points set before continuing.";
}
}
else {
if ([myNodes count]<2) {
errorMsg = #"Please make sure you have at least 2 points set before continuing.";
}
}
if (errorMsg !=nil) {
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"Not enough points"
message:errorMsg
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
// Just dismiss
}];
[alertController addAction:okAction];
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:alertController animated:YES completion:nil];
});
return;
}
ClientLegendDataPointBounds *bounds = [[ClientLegendDataPointBounds alloc] init];
int count = 0;
GeoPoint *first = nil;
NSMutableDictionary *attr = [[NSMutableDictionary alloc] init];
for (_EditAnnotation *anno in myNodes) {
GeoPoint *point = [[GeoPoint alloc] initWithLatitude:[anno coordinate].latitude andLongitude:[anno coordinate].longitude];
[bounds expand:point];
if (count==0) {
first = point;
count++;
continue;
}
NSString *xKey = [NSString stringWithFormat:#"x%d",count-1];
NSNumber *xCoord = [NSNumber numberWithDouble:[point latitude ]];
NSString *yKey = [NSString stringWithFormat:#"y%d",count-1];
NSNumber *yCoord = [NSNumber numberWithDouble:[point longitude]];
[attr setObject:xCoord forKey:xKey];
[attr setObject:yCoord forKey:yKey];
count++;
}
if (count>0) {
NSString *pointCount = [NSString stringWithFormat:#"%d", count-1];
[attr setObject:pointCount forKey:#"pointCount"];
}
[self _setBarThemeDefault];
if (myDataPoint==nil) {
myDataPoint = [myLegend addDataPoint:[NSNumber numberWithLongLong:[DateTime currentTimeInMillis]] title:#"" description:#"" latitude:[first latitude] longitude:[first longitude] attributes:attr type:[myLegend type] bounds:bounds];
dispatch_async(dispatch_get_main_queue(), ^{
[[self navigationController] popViewControllerAnimated:NO];
});
[myHandler newItemCreated:myDataPoint];
} else {
[myDataPoint setAttributes:attr];
[myDataPoint setBounds:bounds];
[myDataPoint setLatitude:[first latitude]];
[myDataPoint setLongitude:[first longitude]];
[myDataPoint setModified:[NSNumber numberWithLongLong:[DateTime currentTimeInMillis]]];
[myDataPoint update];
dispatch_async(dispatch_get_main_queue(), ^{
[[self navigationController] popViewControllerAnimated:YES];
});
[myHandler itemUpdated:myDataPoint];
}
[self _finishSurveyLog:[SurveyLogItem ACT_SAVE_SPATIAL_CONST]];
[self _saveUserLocation];
}
I don't know exactly the plugin but could it be that the plugin itselfs dispatches the ui stuff to the main queue? So you don't have to dispatch the call to the main queue by yourself. Take a look at the source code:
SVProgressHUD.m

collectionView not reloading in parentviewcontroller on removal of childviewcontroller

Any one know how to reload collectionView in parentViewController when removing childViewController.
Here, I am processing on click of button adding childViewController and on click of that childViewController I am getting data and that data will transferred to parentViewController after that child view get's remove from parentViewController.
I am getting data from childViewController, also reloading collection view.
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
});
but, no effect of reloading here seen.
means not able to change parentviewconroller view after removal of childViewController.
Thank you
Waiting for the answer and yes I am doing it in objective c.
parentViewController file.
[self.view addSubview:filterMenuVC.view];
filterMenuVC.view.backgroundColor = [UIColor clearColor];
[self addChildViewController:filterMenuVC];
[self.view addSubview:filterMenuVC.view];
[self animationSideFilterMenuBarOpen];
[filterMenuVC didMoveToParentViewController:self];
childViewController file
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",[NSString stringWithFormat:#"%ld",(long)indexPath.row]);
// // [wel animationSideFilterMenuBarClose];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
int categoryId = (int)cell.textLabel.tag;
[self animationSideMainMenuBarClose:categoryId];
}
-(void)animationSideMainMenuBarClose:(int)categoryId{
CGFloat width = [UIScreen mainScreen].bounds.size.width;
self.view.frame = CGRectMake(width - self.view.frame.size.width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
}
completion:^(BOOL finished){
[self.view removeFromSuperview];
self.view = nil;
NSLog(#"category id Filter: %d",categoryId);
BOOL boolresponse = [wel getUserWork:categoryId];
if (boolresponse == NO) {
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:#"No internet connection"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
here, BOOL boolresponse = [wel getUserWork:categoryId]; getUserWork is the function in parentViewController, I call that and removing the childViewController. get correct data but not able to reload collectionView.
parentViewFunction which I am calling.
-(BOOL)getUserWork:(int)catergoryId{
appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[self dismissViewControllerAnimated:true completion:^{
//do whatever you do here
[self.collectionViewcellItem reloadData];
}];
categoryIdStart = catergoryId;
Reachability *r = [[Reachability alloc]init];
if(r.currentReachabilityStatus != NotReachable) {
return NO;
}
else
{
[SVProgressHUD show];
[SVProgressHUD setStatus:#"Loading..."];
[SVProgressHUD setRingRadius:20];
[SVProgressHUD setRingThickness:10];
[SVProgressHUD setBorderColor:[UIColor orangeColor]];
[SVProgressHUD setBorderWidth:0.5];
[SVProgressHUD setForegroundColor:[UIColor orangeColor]];
NSLog(#"id category: %d",categoryIdStart);
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:[appDelegate.UserDic valueForKey:#"token"],#"token",[appDelegate.UserDic valueForKey:#"id"],#"id_user",[NSString stringWithFormat:#"%d",categoryIdStart],#"id_category",nil];
NSMutableArray *postArray = [NSMutableArray array];
[params enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[postArray addObject:[NSString stringWithFormat:#"%#=%#", key, [apiCall percentEscapeString:obj]]];
}];
NSString *postString = [postArray componentsJoinedByString:#"&"];
[apiCall apiType:#"xyzzy" pD:postString dataRetrive:^(NSDictionary *dictionary){
int status = [[dictionary valueForKey:#"status"] intValue];
if (status == 0) {
[SVProgressHUD dismiss];
dispatch_async(dispatch_get_main_queue(),^{
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:[dictionary valueForKey:#"msg"]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
});
}
else{
[SVProgressHUD dismiss];
[cacheImage removeAllObjects];
dic = [dictionary valueForKey:#"data"];
NSLog(#"Category detail: %# %lu",dic,(unsigned long)dic.count);
NSLog(#"image category %# :",[dic valueForKey:#"category_name"]);
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
[self viewWillAppear:true];
});
}
}];
return YES;
}
}

Integrate iCloud into ios App and Retrieve files from iCloud

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1
But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx
Can any one suggest me.
Follow below steps to integrate iCloud in iOS app and retrieve files.
1. Enable iCloud from your developer account.
2. Create iCloud containers entitlement at developer account.
3. Then just use below code where you want to integrate your iCloud integration.
First of all import #import and add iCloudDelegate delegate then set delegate:
// Setup iCloud
[[iCloud sharedCloud] setDelegate:self];
[[iCloud sharedCloud] setVerboseLogging:YES];
[[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];
[self showiCloudFiles];
then implementation of method showiCloudFiles below
-(void) showiCloudFiles{
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == NO) {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"iCloud Disabled", #"You have disabled iCloud for this app. Would you like to turn it on again?");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:#"Turn On iCloud"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"userCloudPref"];
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
}];
[alert addAction:deleteButton];
[self presentViewController:alert animated:YES completion:nil];
} else {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"Setup iCloud", #"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
After that for downloading file use UIDocumentPickerDelegate method:
#pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
//NSLog(#"%#",url);
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:#"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do further code using fileData
}
}];
[url stopAccessingSecurityScopedResource];
}
}
For UIDocumentPicker visit this link iOS-8-UIDocumentPicker
Follow this guide
https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1
Download sample code at
https://github.com/rwenderlich/PhotoKeeper
Check if iCloud available
- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (_iCloudRoot != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud available at: %#", _iCloudRoot);
completion(TRUE);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud not available");
completion(FALSE);
});
}
});
}
Query type of flies like pdf, doc and docx
- (NSMetadataQuery *)documentQuery {
NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
if (query) {
// Search documents subdir only
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
// Add a predicate for finding the documents
NSString * filePattern = [NSString stringWithFormat:#"*.%#", PTK_EXTENSION];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K LIKE %#",
NSMetadataItemFSNameKey, filePattern]];
}
return query;
}

I want to use identifiers in .m in other .m (implementation file import) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
On cameraviewcontrolle.mr I take a picture or movie using UIImagePickerController. On completion, I call back to aanvraagviewcontroller.m.
I want to save the the picture by tapping on send button.
My question comes to this I think, how can I import .m file or take the picture/movie to aanvraagviewcontroller.m (I use Parse.com to save my PFObjects)?
This is cameraviewcontroller.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was taken/selected!
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
else {
// A video was taken/selected!
self.videoFilePath = (__bridge NSString *)([[info objectForKey:UIImagePickerControllerMediaURL] path]);
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the video!
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil);
}
}
}
[self uploadMessage];
[self dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popToRootViewControllerAnimated:YES];}
- (void)uploadMessage {
NSData *fileData;
NSString *fileName;
NSString *fileType;
if (self.image != nil) {
UIImage *newImage = [self resizeImage:self.image toWidth:320.0f andHeight:480.0f];
fileData = UIImagePNGRepresentation(newImage);
fileName = #"image.png";
fileType = #"image";
}
else {
fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
fileName = #"video.mov";
fileType = #"video";
}
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {// onderdeelAanvraag[#"file"] = file;
// onderdeelAanvraag[#"fileType"] = fileType;
// onderdeelAanvraag[#"recipientIDs"] = self.recipients;
//
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
// Everything was successful!
[self reset];
}
// }];
}
}];
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
[self.recipients removeAllObjects];
}
- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
CGSize newSize = CGSizeMake(width, height);
CGRect newRectangle = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(newSize);
[self.image drawInRect:newRectangle];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
This is aanvraagviewcontroller.m (when send button is pressed, i want to save the picture/movie here);
- (IBAction)verstuurAanvraag:(id)sender {
NSString *onderdeelOmschrijving = self.onderdeelOmschrijvingField.text ;
NSString *autoOmschrijving = self.autoOmschrijvingField.text ;
if ([onderdeelOmschrijving length] == 0 ||
[autoOmschrijving length] == 0)
{
UIAlertView *alertView = [[ UIAlertView alloc] initWithTitle:#"Leeg veld" message:#"Vul de lege velden in" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
else {
PFObject *onderdeelAanvraag = [PFObject objectWithClassName:#"Aanvragen"];
[onderdeelAanvraag setObject:[PFUser currentUser] forKey:#"Aanvrager"];
onderdeelAanvraag[#"OnderdeelOmschrijving"] = onderdeelOmschrijving;
onderdeelAanvraag[#"AutoOmschrijving"] = autoOmschrijving;
NSDate *date = [NSDate date];
onderdeelAanvraag[#"Datum"] =date;
onderdeelAanvraag[#"file"] = file;
onderdeelAanvraag[#"fileType"] = fileType;
onderdeelAanvraag[#"recipientIDs"] = self.recipients;
// Get random number between 0 and 999999
int nummer = arc4random() % 100000;
NSLog(#"nieuw nummer %d", nummer);
[onderdeelAanvraag setObject:[NSNumber numberWithInt:nummer] forKey:#"AanvraagNummer"];
[onderdeelAanvraag saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!" message: [error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
[self performSegueWithIdentifier:#"showRecipients" sender:self];
}
}];
}
}
I SOLVED PASSING UITEXTFIELD TEXT BY THIS ;
I solved passing textfield data passing with the segue method like here ;
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showRecipients"]){
OntvangersViewController *controller;
controller = [segue destinationViewController];
controller.onderdeelOmschrijvingField = self.onderdeelOmschrijvingField;
controller.autoOmschrijvingField = self.autoOmschrijvingField;
controller.image = self.image;
controller.videoFilePath = self.videoFilePath;
NSLog(#"videofilepath %#", self.videoFilePath);
controller.recipients = self.recipients;
}
}
Your question is muddled and confused.
The code in a .m file is not shared with other .m files.
The whole point of the C .h header file is that the header file can be shared, while the implementation (.c, or .m for Objective C) is private, and not shared.
If you want a value to be visible to another class, or another object of the same class, you should define a property in the header file.
If you want to pass a value from one view controller to another, this topic has been covered Ad nauseam here and on other forums. There are at least 2 comments on your post pointing you to other threads covering the topic.

Return value from inside block (Objective-C)

I've been trying to get a value from inside a block for a few hours now, I can't understand how to use the handlers on completion and literally everything.
Here's my code:
+ (void)downloadUserID:(void(^)(NSString *result))handler {
//Now redirect to assignments page
__block NSMutableString *returnString = [[NSMutableString alloc] init]; //'__block' so that it has a direct connection to both scopes, in the method AND in the block
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:#"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) {
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
//NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
returnString = (#"Response was not JSON (from home), it was = %#", [[NSMutableString alloc] initWithData:homeData encoding:NSUTF8StringEncoding]);
//NSLog(returnString);
}
}
else {
//NSLog(#"error: %#", homeError);
}
}];
//NSLog(#"myResult: %#", [[NSString alloc] initWithData:myResult encoding:NSUTF8StringEncoding]);
handler(returnString);
}
- (void)getUserID {
[TClient downloadUserID:^(NSString *getIt){
NSLog([NSString stringWithFormat:#"From get userID %#", getIt]);
}];
}
So I'm trying to NSLog the returnString from the downloadUserID method.
I first tried returning, then I realized you can't do a return from inside a block. So now I've been trying to do it with the :(void(^)(NSString *result))handler to try and access it from another class method.
So I'm calling downloadUserID from the getUserID method, and trying to log the returnString string. It just keeps going to nil. It just prints From get userID and nothing else.
How do I access the returnString that's inside the block of the downloadUserID method?
The problem is not the block itself, the problem is realizing that the block is executed asynchronously.
In your code, at the time you call handler(returnString); the block is probably still executing on another thread, so there's no way you can catch the value at this point.
Probably what you want to do is move that line inside the block (probably at the end, before the closing braces).
You can do this if you write such a wrapper.
In this situation, you need a while loop that will wait for a response from the block.
Method which shoud return value of enum
- (RXCM_TroubleTypes) logic_getEnumValueOfCurrentCacheProblem
{
RXCM_TroubleTypes result = RXCM_HaveNotTrouble;
NetworkStatus statusConnection = [self network_typeOfInternetConnection];
RXCM_TypesOfInternetConnection convertedNetStatus = [RXCM convertNetworkStatusTo_TypeOfInternetConnection:statusConnection];
BOOL isAllowed = [self someMethodWith:convertedNetStatus];
if (isAllowed){
return RXCM_HaveNotTrouble;
}else {
return RXCM_Trouble_NotSuitableTypeOfInternetConnection;
}
return result;
}
Method which calls delegate's method with block.
And waits answer from it.
Here I use while loop. Just check every 0.5sec answer from block
- (BOOL) isUserPermissioned:(RXCM_TypesOfInternetConnection)newType
{
__block BOOL isReceivedValueFromBlock = NO;
__block BOOL result = NO;
__block BOOL isCalledDelegateMethod = NO;
dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_sync(aQueue,^{
while (!isReceivedValueFromBlock) {
NSLog(#"While");
if (!isCalledDelegateMethod){
[self.delegate rxcm_isAllowToContinueDownloadingOnNewTypeOfInternetConnection:newType
completion:^(BOOL isContinueWorkOnNewTypeOfConnection) {
result = isContinueWorkOnNewTypeOfConnection;
isReceivedValueFromBlock = YES;
}];
isCalledDelegateMethod = YES;
}
[NSThread sleepForTimeInterval:0.5];
}
});
return result;
}
Delegate's method in ViewController
- (void) rxcm_isAllowToContinueDownloadingOnNewTypeOfInternetConnection:(RXCM_TypesOfInternetConnection)newType
completion:(void(^)(BOOL isContinueWorkOnNewTypeOfConnection))completion
{
__weak ViewController* weak = self;
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert"
message:#"to continue download on the new type of connection"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:#"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completion(YES);
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:#"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completion(NO);
}];
[alert addAction:cancel];
[alert addAction:ok];
[weak presentViewController:alert animated:YES completion:nil];
});
}

Resources