Making SMS ViewController pop up on iPhone using Unity3D - ios

I am having trouble getting MFMessageCompose to work with Unity3D iOS Plugin.
I got an alert window to pop up with buttons but I am having an error when accessing the MFMessageComposer. Can't seem to get the method to pop up the window properly.
Here is my iOSBridge.h (linked file if you want):
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>
#interface Delegate : NSObject <UINavigationControllerDelegate, MFMessageComposeViewControllerDelegate>
#end
And my iOSBridge.mm file:
#import "iOSBridge.h"
#implementation Delegate
//Trying to still understand the meaning behind this line. Why???
-(id)init
{
return self;
}
//RATE US Button Numbers
//Not entirely sure What I did here but it still bring it up. This section has nothing to do with SMS
-(void) alertView: (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Give back the number of the button
NSString *inStr = [NSString stringWithFormat:#"%d", (int)buttonIndex];
const char *cString = [inStr cStringUsingEncoding:NSASCIIStringEncoding];
UnitySendMessage("Popup", "UserFeedBack", cString);
NSLog(#"%li", (long)buttonIndex);
} // RATE US button number end
-(void)SMS:(id)sender{
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
[controller setMessageComposeDelegate:self];
if([MFMessageComposeViewController canSendText]){
[controller setRecipients:[NSArray arrayWithObjects:nil]];
[controller setBody:[NSString stringWithFormat:#"Text"]];
//WHYYY do you not work
//[self presentViewController:controller animated:YES];
Delegate *appDelegate = UIApplication.sharedApplication.delegate;
[appDelegate.window.rootViewController presentViewController:controller animated:YES completion:nil]
}
}
#end
static Delegate* delegateObject;
extern "C"
{
//A method for unity can run
void _AddNotification(const char* title,
const char* body,
const char* cancelLabel,
const char* firstLabel,
const char* secondLabel)
{
//Don't have a full grasp of this delegateObject thing yet.
if(delegateObject ==nil){
delegateObject = [[Delegate alloc]init];
}
//iOS Alert Pop up view RATE OUR GAME
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: [NSString stringWithUTF8String:title]
message:[NSString stringWithUTF8String:body] delegate:delegateObject
cancelButtonTitle:[NSString stringWithUTF8String:cancelLabel]
otherButtonTitles:[NSString stringWithUTF8String:firstLabel],[NSString stringWithUTF8String:secondLabel], nil];
[alert show];
} //End of _AddNotification
//SMS Method for Unity to use
void _SMSGO(const char* Mbody){
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText]){
NSString *s = [NSString stringWithFormat:#"%s", Mbody];
controller.body = s;
//Suppose to Brings up the SMS view not sure why it isnt working or how to make this work
//If this can work its major progress
[delegateObject presentViewController:controller animated:YES];
}
}
}

So these:
-(void) alertView: (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *inStr = [NSString stringWithFormat:#"%d", (int)buttonIndex];
const char *cString = [inStr cStringUsingEncoding:NSASCIIStringEncoding];
UnitySendMessage("Popup", "UserFeedBack", cString);
NSLog(#"%li", (long)buttonIndex);
}
-(void)SMS:(id)sender{
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
[controller setMessageComposeDelegate:self];
if([MFMessageComposeViewController canSendText]){
[controller setRecipients:[NSArray arrayWithObjects:nil]];
[controller setBody:[NSString stringWithFormat:#"Text"]];
//WHYYY do you not work
//[self presentViewController:controller animated:YES];
Delegate *appDelegate = UIApplication.sharedApplication.delegate;
[appDelegate.window.rootViewController presentViewController:controller animated:YES completion:nil]
}
}
Code blocks are actually not being accessed at all through your bridge. So nothing in this will be touched at all.
The - (id) init is the initializer of the class. So in order to access anything in that file from anything else, you have to init it first. An easier way to think of this is:
extern.c is a separate file.
static Delegate *delObj;
extern "C"
{
void _callMain (const char *hello) {
/**
* delObj is a static so it "Will be once it is" so it will be
* in memory (mallocated) the moment you tell it to be something.
*/
if (!delObj) {
In this case, we want that static object to be an instance of Delegate (not a particularly good name to set your class to, it will lead to much confusion). We "start" or initialize this class by calling init and we tell it this is an object we need, chuck it on the heap read this.
delObj = [[Delegate alloc] init];
}
// Now we can call the function in the next file
[delObj helloWorld];
}
Delegate.m - Think of this as a different file. You can access this file from extern.c because (in reality) it's just included in the same file. But this of this as a separate entity entirely. You have to access this "file" from extern.c
#implementation Delegate
// This is the function we call with [[Delegate alloc] init];
-(id) init {
// It simply returns itself - saying hey this is the object memory chunk in the heap you want to talk to.
return self;
}
// This is the function we call with [delObj helloWorld];
- (void) helloWorld {
NSLog("Hello World"); // This will show up in your console.
}
So the above code has two functions, one that says "this is the memory object your looking for" - one that says "I'm a function, lets execute something".
Now with all that laid out, you're not calling:
-(void) alertView: (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
OR
-(void)SMS:(id)sender{
Via your extern "C". The reason why _AddNotification works is because you have code in there calling UIAlertView AFTER making sure your delegateObject is in memory. In you _SMSGO function, you're not putting your object into memory. So when you call delegateObject in [delegateObject presentViewController:controller animated:YES]; it says "Oh I know what delegateObject is but it's equal to nothing. In fact it does not have memory to execute anything!" Thats why you probably don't get any errors or exceptions. The code knows there is a static object, but it hasn't been set to anything yet.
SOLUTION:
First, void methods don't need :(id)sender thats more of a IBAction thing unless you actually want to send something - so change -(void)SMS:(id)sender{ to - (void) SMS { (with the pretty spacing, too. It's mo' better for eyes).
Second, swap everything in SMS with:
- (void) SMS {
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
[controller setMessageComposeDelegate:self];
if([MFMessageComposeViewController canSendText]){
[controller setRecipients:[NSArray arrayWithObjects:nil]];
[controller setBody:[NSString stringWithFormat:#"Text"]];
// We now know why we work!
[self presentViewController:controller animated:YES];
}
}
But WAIT! And do not copy and paste. Be sure to understand each line of code you write.
This line allocates an object into memory, in this instance, the MFMessageComposeViewController object. Then initializes it.
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
This line sets the delegate of the object we just made (controller). But why can it do this? Because we have MFMessageComposeViewControllerDelegate set in the iOSBridge.h file. This tells everything in your .mm file "hey if we happen to have a MFMessage object somewhere, it may access delegate properties if you want."
[controller setMessageComposeDelegate:self];
if ( [MFMessageComposeViewController canSendText] ) is human readable.
Same with [controller setRecipients:[NSArray arrayWithObjects:nil]]; and [controller setBody:[NSString stringWithFormat:#"Text"]];
But now [self presentViewController:controller animated:YES]; is were we need to dive in.
So in Unity, they said "hey, we don't need to deal with every single possible native function being called" - so they created access to the extern capability for you. This allows you to talk to Objective-C from the UnityScript side of things. Objective-C is just a superset of C, so thats common ground. Everything in here should ONLY call functions in Delegate. The example of this is above in the fake extern.c code block. The only thing that is doing is creating delegateObject and calling a function. Now for the next step. Swap everything in _SMSGO with:
void _SMSGO (const char *mBody) { // I prefer char *name vs char* name but it doesn't matter
[delegateObject SMS]; // add mBody as a parameter when you're ready. Handle the stringWithUTF8String on the Objective-C side of things. Yes, this is not the Obj-C side, this is the C side.
}
"But wait... you just delegateObject needs to be a thing" - Yes it does. Create another method in your extern "C" section called _init and run this one time from Unity in the Awake or Start function of your class. This will set your static object one time and never mess with it again. Simply make it:
void _init() {
if ( !delegateObject ) {
delegateObject = [[Delegate alloc] init];
}
}
!delegateObject is the same thing as delegateObject == nil but cleaner code. Both say "We don't know what dat is" - Ok now we have our delegateObject, we are free to make our next calls with delegateObject as much as we'd like.
Now when you call [delegateObject SMS] it goes to - (void) SMS. And when you call self presentViewController it knows that self is referring to an iOS Native Object. If you call presentViewController in extern "C" it says "... um, hmm. I haven't got the foggiest notion what that means" - for this reason, we have use everything in your extern "C" section as a crossover to your Delegate object. That is the whole purpose of the extern thing, just to call things in your Obj-C stuff.
Hope this helps.

Related

Hook to an instance method in iOS using theos and retrieve the argument that is being passed

-(void)setID:(long long) is the method and I want retrieve the argument (the integer) being passed and show it in an alert view. I am new to this please help me. And also if possible, how to pass this argument to a different method.
-(void)setSelectedID:(long long), if this is the method I want to pass the arguments to, how would I do it in the Tweaks.xm file.
Any help would be appreciated, thanks.
Can this also be done using Cycript?
this code is untested but I hope it can help (assuming that setSelectedID: is a method that you made) :
// Use parenthesis to avoid creating a duplicate definition of TheClassToHook
#interface TheClassToHook ()
// Put your new method definitions here
- (void)setSelectedID:(long long)passedID;
#end
%hook TheClassToHook
// This is the original method from TheClassToHook
- (void)setID:(long long)passedID {
// Call your new method
[self setSelectedID:passedID];
// Create an NSString from the passed id,
// it will be used to show it in the alert as a message
NSString *msg = [NSString stringWithFormat:#"%lld", passedID];
// Show an alert using UIAlertView, note that TheClassToHook should implement UIAlertViewDelegate
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"The passed id is..."
message:msg
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// Optional: Make sure the memory used to allocate the alert and its message are released,
// this may be unnecessary
[alert release];
[msg release];
/* NOTE:
UIAlertView is deprecated since iOS 8,
if you don't want to target older iOS versions,
you should consider using UIAlertController instead
*/
// Call the original method with the original arguments
%orig;
}
// Use the "%new" logos directive to implement a new method
%new
- (void)setSelectedID:(long long)passedID {
// Your code
}
%end // close %hook
If setSelectedID: is a method that is present by default, you can just remove its definition from the #interface block and its implementation in the %hook block.
Also, since I don't use Cycript, I don't know if it can be done using it, sorry.

unit test local objects or dependency injection with OCMock?

Trying to create simple test for following function:
-(void)presentWithString:(NSString *)name
{
CustomVC *customVC = [[CustomVC alloc] initWithName:name];
UINavigationController *nav = [[UINavigationController alloc] init];
nav.viewControllers = #[customVC];
dispatch_async(dispatch_get_main_queue(), ^{
[self.vc presentViewController:nav animated:YES completion:nil];
});
}
I can split this into chunks with dependency injection, but don't know how to write proper test either way. What would be the best practice for this example?
What do you want to test? There are 3 things happening in your method :
CustomVC is created with name passed.
CustomVC is embedded inside navigation controller.
The navigation controller is presented on self.vc.
You can write a test that checks the whole flow :
- (void)testPresentWithString_shouldPresentCustomVC_withPassedName {
// Arrange
NSString *expectedName = #”name”;
XCTestExpectation *exp = [self expectationWothDescription:#”presentVC called”];
TestClass *sut = [[TestClass alloc] init];
id vcMock = OCMClassMock([UIViewController class]);
sut.vc = vcMock;
OCMExpect([vcMock presentViewController:OCM_ANY animated:YES completion:nil]).andDo(^(NSInvocation *invocation) {
UINavigationController *nav = nil;
[invocation getArgument:&nav atIndex:2];
CustomVC *custom = nav.viewControllers.firstObject;
// Assert
XCTAssertNotNil(nav);
XCTAssertTrue([nav isKindOfClass:[UINavigationController class]]);
XCTAssertEqual(nav.viewControllers.count, 1);
XCTAssertNotNil(custom);
XCTAssertTrue([custom isKindOfClass:[CustomVC class]]);
XCTAssertEqual(custom.name, expectedName);
[exp fulfill];
});
// Act
[sut presentWithString:expectedName];
// Assert
[self waitForExpectationsWithTimeout:1 handler:nil];
OCMVerifyAll(vcMock);
// Cleanup
[vcMock stopMocking];
}
This code checks everything that happens in your method - that a method got called with specific arguments, that the first of these arguments was a navigation controller with only CustomVC embedded and that this CustomVC had name set. Obviously I’ve made assumptions that vc property on tested class can be set from outside and that the name on CustomVC can be read. If not, it may be trickier to test some parts of this.
Personally I wouldn’t unit test this. I would test the initialization of CustomVC separately, and put the whole presentation under a UI test.
Let me know if everything is clear!
—
Side note : I wrote this on mobile from memory, so there might be small mistakes in the code. I will update it when I have a chance to check it with Xcode.

How to send two or more SMS messages in iOS, in synchronized fashion

I am relatively new to iOS development and have a question.
I have the need to send a multi part SMS message. I understand that I can just take the long message and pass that into the 'MFMessageComposeViewController' and it will break everything up for me accordingly. However, that will not work, because every message that I send has a specific delimiter and I need every single one of the messages to begin with that identical delimiter. So, what I have tried to do is use a for loop, and display each controller after the other. However, my 'MfMessageComposeViewController' for the other message parts is not being displayed, it only shows the initial message. The warning that is displayed in the terminal is this
"Attempt to present < MFMessageComposeViewController: 0x126819200> on < ViewController: 0x12660ae80> which is waiting for a delayed presention of < MFMessageComposeViewController: 0x12683b200> to complete"
Any suggestions? I tried using code blocks and synchronizing everything so that each Controller would be displayed in a synchronized fashion, however that did not work. Code is below
NSMutableArray *strings = [SmsBuilder createSMS:160 StringToConvert: AddOrEdit:#"PersonAdd"];
void (^send)(NSString *) = ^(NSString *str){
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc]init];
#synchronized(controller){
[controller setBody:str];
[controller setMessageComposeDelegate:self];
[controller setRecipients:[NSArray arrayWithObjects:#"111-111-1111", nil]];
[self presentViewController:controller animated:YES completion:^(void){}];
}
};
for(int i=0;i<[strings count];i++) send([strings objectAtIndex:i]);
MFMessageComposeViewController has a delegate protocol which will inform you when it has completed sending. You need to dismiss the viewcontroller in this method and from that completion block, show the next part.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result {
[controller dismissViewControllerAnimated:YES completion:^{
[self showNextMessagePart];
}];
}

Objective-C Passing NSURL to another viewcontroller

I have two view controllers: FirstViewController and SecondViewController. The project is to record a video and attach it to an email. I can record it and have it able to email, I just need to attach it. I am able to get a URL for the video in FirstViewController, but passing it isn't working.
FirstViewController -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.movie"])
{
// Saving the video to phone / // Get the new unique filename
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath, self, /*#selector(video:didFinishSavingWithError:contextInfo:)*/nil, nil);
self.movieURL= [[NSURL alloc] initFileURLWithPath: sourcePath];
NSLog(#"movieURL");
NSLog(self.movieURL.absoluteString);
SecondViewController *sendMovie = [[SecondViewController alloc] initWithNibName:#"ViewController" bundle:nil];
sendMovie.movieU = [[NSURL alloc] initFileURLWithPath: sourcePath];
[[self navigationController] pushViewController:sendMovie animated:YES];
NSLog(#"movieU");
NSLog(sendMovie.movieU.absoluteString);
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
SecondViewController to attach to email -
NSLog(#"1st print");
NSLog(self.movieU);
[controller addAttachmentData:[NSData dataWithContentsOfURL:self.movieU] mimeType:#"video/MOV" fileName:#"defectVideo.MOV"];
NSLog(#"2nd print");
NSLog(self.movieU.absoluteURL);
[self presentViewController:controller animated:YES completion:nil];
SecondViewController.h property of NSURL
#property(nonatomic) NSURL *movieU;
The movieURL is a property in the FirstViewController, but I don't believe is needed.
I can see the URL in the FirstVC, but it appears nil in the SecondVC.
Solutions -
1) define NSURL *movieU as a extern instead of property.
2) else define it as a property of AppDelegate and access it.
3) or else synthesize property movieU and do allocate like -
in your FirstViewController -
SecondViewController *sendMovie = [[SecondViewController alloc] initWithNibName:#"ViewController" bundle:nil];
NSURL *url = [[NSURL alloc] initFileURLWithPath: sourcePath];
sendMovie.movieU = url;
[[self navigationController] pushViewController:sendMovie animated:YES];
And NSLog it in your SecondViewController.
Hope this helps!
There is nothing wrong with the way you are going about passing information. Try this:
// In you code where you create the second view controller.
SecondViewController *sendMovie = [[SecondViewController alloc] initWithNibName:#"ViewController" bundle:nil];
// SecondViewController viewDidLoad method being called (movieU is still nil)
sendMovie.movieU = [[NSURL alloc] initFileURLWithPath: sourcePath];
// Do a nil test here
if (!sendMovie.movieU) {
NSLog(#"%#",#"It's nil here!"); // If this is the case something is wrong with "sourcePath"
} else {
NSLog(#"%#",#"It's not nil here!");
}
[[self navigationController] pushViewController:sendMovie animated:YES];
// SecondViewController viewWillAppear method being called (movieU is NOT nil)
// SecondViewController viewDidAppear method being called (movieU is NOT nil)
This test will tell you a lot. If its nil here then the problem is not with setting the second view controller's property but with actually creating the NSURL object. It could be a lot of things like you are overwriting it somewhere in the second view controller (e.g. viewWillAppear method). Just follow the trail using break points, logging, etc. to follow its life time.
Edit - Debugging Procedure
Set break points where you create Second VC, set its property, push it, and finally view it (clicking on the tab). Set break points throughout the lifecycle of the second VC (viewDidLoad, viewWillAppear, viewDidAppear, etc). This will allow you to step through the entire lifecycle of your VC. If you haven't utilized those methods go ahead and define them anyway including a call to super. As you step through these break points keep checking the value of movieU. You will see it is nil at first, then you set it (we know this from your comments), its not nil, then it becomes nil, again, etc. If you are patient and systematic you will find it and learn a whole lot about the lifecycle of VCs. If you don't systematically step through you may miss something. For instance maybe your code is creating a whole new Second VC when you click on the tab to actually look at it. Stepping through your code this way will show that.
Edit
Make sure you are testing in the viewWillAppear/viewDidAppear methods or later so that the property has actually been set. See comments in my code.
Edit
A property of retainable object pointer type which is synthesized without a source of ownership has the ownership of its associated instance variable, if it already exists; otherwise, [beginning Apple 3.1, LLVM 3.1] its ownership is implicitly strong. Prior to this revision, it was ill-formed to synthesize such a property.
From: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#property-declarations
According to this (unless you are specifying weak on the ivar - unlikely) it should be strong by default.
Good luck.
use this
self.movieURL = [NSURL fileURLWithPath:sourcePath];
instead of
self.movieURL= [[NSURL alloc] initFileURLWithPath: sourcePath];
hope this work
I got it fixed! I decided to use a singleton which uses a shared instance through another class. I created a whole new class called Singleton and only contained the sharedinstance method:
+ (id)sharedInstance {
static id sharedInstance = nil;
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
Singleton.h
#property NSURL *movieU;
+ (id)sharedInstance;
Make sure to import the singleton class to both First and Second VC.
SecondVC.m
Singleton* single = [Singleton sharedInstance];
[controller addAttachmentData:[NSData dataWithContentsOfURL: single.movieU] mimeType:#"video/MOV" fileName:#"defectVideo.MOV"];
FirstVC.m
Singleton* single = [Singleton sharedInstance];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.movie"]){
// Saving the video / // Get the new unique filename
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath, self, /*#selector(video:didFinishSavingWithError:contextInfo:)*/nil, nil);
self.movieURL = [[NSURL alloc] initFileURLWithPath: sourcePath];
NSLog(#"movieURL");
single.movieU = self.movieURL;
By doing this, it successfully would pass the url containing the information for the recorded video to be attached to the email.

Variable lost after dismissing modalViewController

I'm using Reachability in my iPad app and discovered some issues when using modalViewControllers.
In my mainViewController I have a BOOL variable determining weather I'm online or not. Here's my code:
// mainViewController.h
BOOL online;
// mainViewController.m
- (void)reachabilityChanged:(NSNotification *)note
{
if([[note object] isReachable]) {
online = YES;
}
else {
online = NO;
}
}
- (void)getOnline
{
NSLog(#"%d", online);
}
// modalViewController.m
#import "mainViewController.h"
- (IBAction)dismissMe
{
mainViewController *main = [[mainViewController alloc] init];
[main getOnline];
[self dismissModalViewControllerAnimated:YES];
}
When I'm calling [self getOnline] within the mainViewController, it returns 1 ('cause I am online).
But: when I'm calling [main getOnline] within the modalViewController, it returns 0 in the log.
Does anybody know why?!
I also tried to put the online variable as a #property into the modalViewController to handle the if online stuff within the modal. But when I assign a value to it (from the main), and log it within the modal, it always returns (NULL).
Hope, you can help me! With best regards, Julian
Short answer: because they use different instances of the online variable.
Long answer: you should only declare BOOL online in the header, not define it. Defining should happen in the .m file, like this:
In the mainViewController.h:
extern BOOL online; // Declare the variable
In the mainViewController.m:
BOOL online; // Define the variable
// the rest of your code
The way your code is written, a separate BOOL online is created for each .m file that includes mainViewController.h; I am sure this is not what you intended.

Resources