<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" >

<channel><title><![CDATA[Absolute Ripple - Resources]]></title><link><![CDATA[https://www.absoluteripple.com/resources]]></link><description><![CDATA[Resources]]></description><pubDate>Sun, 20 Sep 2026 09:03:46 +1000</pubDate><generator>Weebly</generator><item><title><![CDATA[Block Based Completion Handler]]></title><link><![CDATA[https://www.absoluteripple.com/resources/block-based-completion-handler]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/block-based-completion-handler#comments]]></comments><pubDate>Sun, 11 Aug 2013 12:13:43 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/block-based-completion-handler</guid><description><![CDATA[If you have used some of iOS methods that uses block you would probably agree that they are quite wonderful to use. I am talking about methods such as these:[UIView animateWithDuration:5.0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; animations:^{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // some code&nbsp;&nbsp;&nbsp;&nb [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">If you have used some of iOS methods that uses block you would probably agree that they are quite wonderful to use. I am talking about methods such as these:<br />[UIView animateWithDuration:5.0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; animations:^{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // some code<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } completion:^(BOOL finished) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // some code<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }];<br /><br />[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // some code<br />&nbsp;&nbsp;&nbsp; }];<br /><br /><span>Blocks enable you to write more compact and flexible </span>codes that can be easily reused in your programs. It does take awhile to get use to the most weird looking syntax though. <br /><span></span><br /><span></span>Then you start to think, wouldn't it be nice if I could use a block based completion handler in some of my methods. But how? It looks so confusing and you just don't know where to begin. The block syntax makes it appears harder than it really is. The basic pattern is simple.<span></span><br /></div>  <h2 style="text-align:left;"><font size="4">The Pattern</font><br /></h2>  <div class="paragraph" style="text-align:left;"><strong>1. Typedef the block</strong><br /><span></span><font color="#6cb83a">typedef void (^NameOfYourCompletionHandler)(NSString *name, BOOL finished);</font><br /><span></span>This block calls 'NameOfYourCompletionHandler'. It has two arguments - an NSString and a BOOL. Obviously, you can have more or less arguments to suit your situation.<br /><span></span><br /><strong>2. Add a property</strong><br /><font color="#6cb83a">@property (nonatomic, copy) NameOfYourCompletionHandler nameOfYourCompletionHandler;</font><br /><span></span>This is just like how you define any other property. i.e. preceding the name of the property with the type (i.e. NameOfYourCompletionHandler here). The name of the property can be whatever you like. If the code uses only one property of this block type, it is generally preferable to keep the property name the same as the name of the type (and lower casing the first character) to make it easier to follow.<br /><span></span><br /><strong><span>3. Create an instance method (not a class method) that takes the block as one of its argument</span></strong><br /><font color="#6cb83a">- (void)doSomeTask:(NSString *)taskName withCompletion:(NameOfYourCompletionHandler)completionBlock<br />{<br />&nbsp;&nbsp;&nbsp; self.nameOfYourCompletionHandler = completionBlock;<br />&nbsp;&nbsp;&nbsp; // code to do something<br />}<br /></font>The line self.nameOfYourCompletionHandler = completionBlock is important as this copies the completionBlock code to the instance variable so that it can be invoked later.<br /><span>As noted above, this <em>cannot</em> be a class method as a class method would have any instance variables, such as the </span>nameOfYourCompletionHandler here. If you must use a class method, you need to use static storage instead.<br /><span></span><br /><strong><span>4. Call the completion block when you want to invoke it.</span></strong><br /><span></span><font color="#6cb83a">self.nameOfYourCompletionHandler(@"some name", YES);</font><br />This simply calls the completion block code and passes in the arguments.<br /><span></span><br /><span>This is all you need. And you can use the block based instance method like this, assuming you are invoking it within the same class:</span><br /><span></span><font color="#6cb83a">[self doSomeTask:@"some task name" withCompletion:^(NSString *name, BOOL finished) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // code you want to perform <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // i.e. code you want to execute when the completion block is invoked under (4) above. &nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; }];</font><br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <br /><span></span>Looking around online you will come across slight variation to the above, but the underlying pattern is the same. Some don't use typedef, and some don't use property (using static storage instead). <br /><br /><strong><span>Without Typedef</span></strong><br /><span>Without using typedef, (2) would look like:</span><br /><font color="#6cb83a">@property (nonatomic, copy) void (^nameOfYourCompletionHandler)(NSString *, BOOL)</font><br /><br /><span></span><span>And (3) would look like:</span><br /><font color="#6cb83a">- (void)doSomeTask:(NSString *)taskName withCompletion:(void(^)(NSString *name, BOOL finished))completionBlock<br />{<br />&nbsp;&nbsp;&nbsp; self.nameOfYourCompletionHandler = completionBlock;<br />&nbsp;&nbsp;&nbsp; // code to do something<br />}</font><br /><span></span>The rest would be the same.<br /><span></span><br /><span></span> Typedef makes the code looks cleaner (i.e. less weird syntax). However, it is just a personal preference/ coding style thing.<br /><br /><strong><span>Using Static Storage</span></strong><br /><span></span>If you want to use block with class method you can do so with static storage.<br /><span>Instead of (2), you would declare the static storage as follows in your implementation file:</span><br /><font color="#6cb83a"><span>static </span>NameOfYourCompletionHandler _nameOfYourCompletionHandler;</font><br /><span></span>And (3), would look like:<br /><font color="#6cb83a">+ (SomeClass*)doSomeTask:(NSString *)taskName withCompletion:(NameOfYourCompletionHandler)completionBlock<br />{<br />&nbsp;&nbsp;&nbsp; </font>_<font color="#6cb83a">nameOfYourCompletionHandler = [completionBlock copy];<br />&nbsp;&nbsp;&nbsp; // code to do something<br />}</font><br /><span>And (4) becomes:</span><br /><font color="#6cb83a">_nameOfYourCompletionHandler(@"some name", YES);</font><br /><br /><strong><span>Other Useful Reference About Using Block</span></strong><br /><span>- <a target="_blank" href="http://yannickloriot.com/2011/11/working-with-blocks">Working with Blocks</a></span><br /><span>- <a target="_blank" href="http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1">Using Blocks in iOS 4: The Basics</a></span><br /></div>]]></content:encoded></item><item><title><![CDATA[Using IOS Storyboard Segues]]></title><link><![CDATA[https://www.absoluteripple.com/resources/using-ios-storyboard-segues]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/using-ios-storyboard-segues#comments]]></comments><pubDate>Fri, 02 Aug 2013 06:04:22 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/using-ios-storyboard-segues</guid><description><![CDATA[Using storyboard to set up the design of the various views is the way to go in most apps these days for iOS app development. The friendly graphical interface makes it quite easy to use. After using it for awhile, you wonder why you would ever want to go back to a code base approach (although there may be some situations where you may still want to do things purely in code). Segues are used when you want to:1. Go to another view controller - it does this by instantiating a view controller you set [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">Using storyboard to set up the design of the various views is the way to go in most apps these days for iOS app development. The friendly graphical interface makes it quite easy to use. After using it for awhile, you wonder why you would ever want to go back to a code base approach (although there may be some situations where you may still want to do things purely in code). <br /><br /><span>Segues are used when you want to:</span><br /><span>1. Go to another view controller</span> - it does this by instantiating a view controller you set up and link to in the storyboard. The new view controller can be presented in different ways: modal, push (when embedded within a UINavigationController), popover, or embedded (such as in a container view).<br /><span>2. Go back to a view controller </span>that directly or indirectly presents the current view controller. This is the unwind segues.<br /><span>3. Pass values or objects between view controllers as you are going to a view controller or unwinding to a previous view controller.</span><span> Using the segues to pass values or objects between view controllers is very convenient, especially passing values or objects back to a prior view controllers. Without using segues, passing values or objects back to a prior view controller would require the use of protocol and delegates or some notification services. Segues often provide a more elegant and simpler (i.e. less code) way to </span>achieve this.<br /><span></span><br /><span>Setting up the actual storyboard in Xcode is easy enough</span>, but getting your code to work with it or talk to it is something else; it is not hard, you just need to know how. There are many very useful tutorials online about various aspect of it. The aim here is not to recreate those tutorials. This is a brief summary of the various things that are commonly performed and codes snippets that are often used. <br /></div>  <h2 style="text-align:left;">Going to Another View Controller<br /></h2>  <div class="paragraph" style="text-align:left;">The example here assumes the following setup: <br /><ul style=""><li style="">There are three view controllers - ViewControllerOne, ViewControllerTwo&nbsp; and ViewControllerThree. <br /></li><li style="">These are all embeded within an UINavigationController.</li><li style="">Clicking  a button on ViewControllerOne will go to ViewControllerTwo via a push  segue. Likewise, clicking a button in ViewControllerTwo will go to  ViewControllerThree via a push segue.<br /></li></ul>The Storyboard looks like this:</div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/4022234_orig.jpg" alt="Storyboard " style="width:100%;max-width:892px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;">The approach described below also work without the UINavigationController and where modal segues are used to go from ViewControllerOne to ViewControllerTwo and from ViewController Two to ViewControllerThree.<br /><br /><span><strong>Creating the segues:</strong> control drag from the relevant button to the view controller you want to show.</span><br /><strong><span>Code in the source view controller:</span></strong> (i.e. the controller you are originating from)<br /><span></span><font color="#6cb83a">- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender<br />{<br />&nbsp;&nbsp;&nbsp; if ([segue.identifier isEqualToString:@"ViewControllerTwoSegue"]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ViewControllerTwo *vc2 = (ViewControllerTwo *)segue.destinationViewController;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; vc2.name = self.textField.text;<br />&nbsp;&nbsp;&nbsp; }<br />}</font><br /><span>where</span>:<br /><span>- </span>'ViewControllerTwoSegue' is the name of the segue set in storyboard<br /><span>- 'ViewControllerTwo' is the class of the destination view controller</span> (i.e. the view controller you are going to)<br /><span>&nbsp;</span><br /><strong><span>Passing values or objects</span></strong>: set the relevant property in the destination view controller inside the prepareForSegue method<br /><span>In </span><span>this example, ViewControllerTwo has a public property called 'name' (an NSString in this case). Here it is set to the value of a text field called 'textField' in ViewControllerOne.</span><br /><br /><span>Note: when the prepareForSegue method is called, the views </span>in the destination view controller may <em>not</em> have been fully instantiated yet. This means it is often <em>not</em> a good idea to directly set the values of views (such as a text filed or label) in the destination view controller inside the prepareForSegue. e.g. if View Controller Two has a text field called 'textField', this may not work: vc2.textFeild.text = self.textField.text, or may work unreliably. It is often better to set the value of a property in the destination view controller and then set the text filed or label inside viewDidLoad of View Controller Two.<br /><br /></div>  <h2 style="text-align:left;">Going to Another View Controller Conditionally<br /></h2>  <div class="paragraph" style="text-align:left;">Most of the time you want to go directly to a view when a button is clicked, but this is not always the case. Sometimes you may want to go to a view only under certain condition. Obviously, one way is to disable the button unless the condition is satisfied, but another is to stop the segue.<br /><span></span><strong>Stopping the segue:</strong> return NO for <font color="#3a96b8">shouldPerformSegueWithIdentifier</font>:<br />The code:<br /><font color="#6cb83a">- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender<br />{<br />&nbsp;&nbsp;&nbsp; if ([identifier isEqualToString:@"ViewControllerTwoSegue"]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return NO;<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; return YES;<br />}</font><br /><span></span>where:<br />- 'ViewControllerTwoSegue' is the name of the segue set in storyboard<br /><span></span><br /><span></span>This method is invoked automatically by iOS before it calls prepareForSegue. This allows you to put conditional codes in it, to determine whether to actually perform the segue. The above code will prevent the user from going to ViewControllerTwo ever. This is probably not what you want to do all the time. In real code, you need to change 'return No' to something else that return NO or return YES based on some conditions that suit your app.<br /><span></span><br /></div>  <h2 style="text-align:left;">Passing Values or Objects<br /></h2>  <div class="paragraph" style="text-align:left;">Values or objects can be passed along to the view controller that you are going to (i.e. the destination view controller) by simply setting one or more public property in the destination view controller, such as the 'name' property in the example above.<br /><span>The above code only works in situation where the view you are going to is a UIViewController. The above won't work if you are going to a UINavigationController. Consider, for example, you start from a&nbsp; ViewController</span> and the segue is connected to another view controller (say ViewControllerOne) that is itself embedded within a UINavigationController. The code above won't work because the object return by the destinationViewController property of the segue is <em>not</em> a UIViewController; it is in fact a UINavigationViewController. For this type of setup, use this code inside prepareForSegue:<br /><span></span><br />&nbsp;&nbsp;&nbsp; <font color="#6cb83a">if ([segue.identifier isEqualToString:@"ViewControllerOneSegue"]) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if ([segue.destinationViewController isKindOfClass:[UINavigationController class]]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UINavigationController *navController = segue.destinationViewController;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ViewControllerOne *vc1 = [navController.viewControllers objectAtIndex:0];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; vc1.name = self.textField.text;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font><br />where:<br /><span></span>- 'ViewControllerOneSegue' is the name of the segue set in storyboard<br />The above code snippet also did a bit of introspection to confirm that the destination view controller is in fact a UINavigationController, but this is optional and not required if you know that the segue will always go to a UINavigationController. <br /><br /><span></span><br /></div>  <h2 style="text-align:left;">Going Back To Another View Controller - aka Unwinding<br /></h2>  <div class="paragraph" style="text-align:left;">With segues we can go back to another view controller just as easy. Not only can we go back to the previous view controller (i.e. the view controller that was shown immediately before the current one), we can go <em>back</em> to any other view controllers. This is done via the unwind segue. <br /><span></span><br /><span></span>This mechanism is only to go <em>back</em> to one of the previous view controller, hence the name unwind segue; it is not design to go to any other view controller that you may have on the Storyboard. Unlike other segues, unwind segues do not instantiate a view controller; they go to an existing view controller only. There is no limit to how far back you can unwind, but the view controller that you are going back to must be one that lies along the chain of view controllers leading to the presentation of the current view controller.<br /><span></span><br /><span></span>Setting up the unwind segue is slightly less intuitive than setting up a segue that go to another view controller. The steps are:<br /><span>1. </span>Implement an IBAction method in the view controller that you want to unwind to;<br /><span>2. </span>Link this method to a button in the view that you want to unwind from.<br /><span></span><br /><span>The following code example demonstrates going from ViewControllerThree to ViewControllerOne by clicking a button in ViewControllerThree.</span><br /><span></span><br /><span><strong>Add an IBAction: </strong>(put this inside the view controller that you want to return or unwind back to)</span><br /><span></span><font color="#6cb83a">&nbsp;&nbsp;&nbsp; - (IBAction)backToViewControllerOne:(UIStoryboardSegue *)segue<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"from segue id: %@", segue.identifier);<br />&nbsp;&nbsp;&nbsp; <span>}</span><br /></font><br />This method essentially provides the means for ViewControllerThree to talk to ViewControllerOne. The method name (i.e.'backToViewControllerOne'&nbsp; here) can be anything you want so long that it takes one argument of the type <font color="#3a96b8">UIStoryboardSegue</font> and the return type is IBAction This is all that is required in terms of code (you don't need the NSLog of course). Additional codes are only required if you want to pass values or objects back. <br /><span></span><br /><strong><span>Link it up in StoryBoard:</span></strong><br /></div>  <span class='imgPusher' style='float:right;height:0px'></span><span style='z-index:10;position:relative;float:right;;clear:right;margin-top:0px;*margin-top:0px'><a><img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/8789784.jpg" style="margin-top: 5px; margin-bottom: 10px; margin-left: 10px; margin-right: 0px; border-width:0;" alt="Unwind segue" class="galleryImageBorder" /></a><span style="display: block; font-size: 90%; margin-top: -10px; margin-bottom: 10px; text-align: center;"></span></span> <div class="paragraph" style="text-align:left;display:block;">In the Storyboard, assuming you have a button that you want to click to  start the unwind action, control-drag from that button to the green  'exit' icon on the bottom of the view controller that you are unwinding  from. In the example here, it is ViewControllerThree. A popup menu will  appear, and one of the selection would be the name of the IBAction  method. Here, it would be backToViewControllerOne.<br /><br />Sometimes,  however, the method name you have entered just won't show up. And this makes  it somewhat confusing especially when you first learn to use this  unwind segue thing. Not sure why this is the case; but it sure feels  like a bug in Xcode. The fix is to simply close the project and reopen  it; occasionally, restarting Xcode may also be required. <br /><br />Once  it is all link up, it should work. In the example here, clicking the  button will then take you directly back to ViewControllerOne.</div> <hr style="width:100%;clear:both;visibility:hidden;"></hr>  <div class="paragraph" style="text-align:left;"><strong style="">Passing values or objects back:</strong> simply  access the relevant public property in the view controller you are  returning from (referred to as the source view controller).<br />For example, you can use code like:<br />&nbsp;&nbsp;&nbsp; <font color="#6cb83a">- (IBAction)backToViewControllerOne:(UIStoryboardSegue *)segue<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"from segue id: %@", segue.identifier);<br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if ([segue.sourceViewController isKindOfClass:[ViewControllerThree class]]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"from view controller three");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ViewControllerThree *vc3 = segue.sourceViewController;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.textField.text = vc3.name;<br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</font><br />This  example simply sets the value of the text field called textField in the  current view controller (ViewControllerOne) to the value of a property  called 'name' in ViewControllerThree.<br /><br />The above code  uses introspection to determine which view controller the segue is  returning from. Introspection is not essential, but can be handy for  writing generic code that can handle unwinding from multiple view  controllers. <br /><br />If you need to set the value of the relevant  property in ViewControllerThree to a  particular value, this is can be done by the prepareForSegue method in  ViewControllerThree. Suppose you want to set the property called 'name'  above, you can do the following:<br />&nbsp;&nbsp;&nbsp; <font color="#6cb83a">- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if ([segue.identifier isEqualToString:@"Vc3ToVc1Segue"]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.name = self.textField.text;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</font><br /></div>  <span class='imgPusher' style='float:right;height:0px'></span><span style='z-index:10;position:relative;float:right;;clear:right;margin-top:0px;*margin-top:0px'><a><img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/2218729.jpg" style="margin-top: 5px; margin-bottom: 10px; margin-left: 10px; margin-right: 0px; border-width:1px;padding:3px;" alt="Document outline with unwind segue" class="galleryImageBorder" /></a><span style="display: block; font-size: 90%; margin-top: -10px; margin-bottom: 10px; text-align: center;"></span></span> <div class="paragraph" style="text-align:left;display:block;">where:<br />- Vc3ToVc1Segue is the name of the unwind segue. Setting  the  name of this segue gets a bit confusing. You set the name in the   Storyboard by clicking on the segue in the so called 'Document Outline'   on the left hand side of the Storyboard. This segue is not shown in the   diagrammatic representation. Once the unwind segue is linked, it will   be shown in the Document Outline, usually beginning with the words   "Unwind segue from...". Clicking on that will allow you to set its name in the attribute inspector.<br /><br />This simply sets  the name property to the  value in the text field called 'textField'.  Together with the code in  the backToViwControllerOne method above, this  passes the value of the  text field in ViewControllerThree back to  ViewControllerOne via the  unwind segue. This approach is much simpler  than a protocol and  delegate based approach.</div> <hr style="width:100%;clear:both;visibility:hidden;"></hr>  <div class="paragraph" style="text-align:left;"></div>]]></content:encoded></item><item><title><![CDATA[Grand Central Dispatch]]></title><link><![CDATA[https://www.absoluteripple.com/resources/grand-central-dispatch]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/grand-central-dispatch#comments]]></comments><pubDate>Tue, 23 Jul 2013 07:56:51 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/grand-central-dispatch</guid><description><![CDATA[Grand Central Dispatch (GCD) is a powerful multitasking technology in iOS. I don't pretend to know all the ins and outs about GCD, and haven't really use it much. Mostly, I tend to use it for just one thing: to prevent the main thread from blocking due to time consuming activities, such as downloading things from the network or serious image processing.   The code typically looks something like:dispatch_queue_t nameOfQueue = dispatch_queue_create("SOME_NAME", NULL);&nbsp;&nbsp;&nbsp; dispatch_as [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">Grand Central Dispatch (GCD) is a powerful multitasking technology in iOS. I don't pretend to know all the ins and outs about GCD, and haven't really use it much. Mostly, I tend to use it for just one thing: to prevent the main thread from blocking due to time consuming activities, such as downloading things from the network or serious image processing. <br /></div>  <div class="paragraph" style="text-align:left;">The code typically looks something like:<br /><font color="#6cb83a">dispatch_queue_t nameOfQueue = dispatch_queue_create("SOME_NAME", NULL);<br />&nbsp;&nbsp;&nbsp; dispatch_async(nameOfQueue, ^{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* codes to be performed in the other queue */</font><br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <font color="#6cb83a">/* eg. downloading something&nbsp; */</font><br /><span></span><font color="#6cb83a">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; dispatch_async(dispatch_get_main_queue(), ^{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* codes to be performed in main thread, usually UIKit stuff */<br />&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; /* e.g. update the UI based on the data you have downloaded */<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<br />&nbsp;&nbsp;&nbsp; });</font><span></span><br /><span></span><br /><span>Note:</span><br /><span>- the NULL in dispatch_queue_create means this is a serial queue, as opposed to a concurrent queue</span><br /><span></span>- dispatch_get_main_queue() is used to get the main queue<br /><span>- </span>dispatch_get_current_queue() is used to get the current queue<br /><span></span><br /><span>It is important to dispatch back to the main queue if you want to run UIKit stuff as they are mostly <strong>not</strong> thread safe. This is what the second dispatch_async() is doing above. A few exceptions are: UIImage</span>, UIFont, UIBezierPath, drawing things using Core Graphics. (Not sure if there are others.)<br /><br /><span>See the <a target="_blank" href="https://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html">Apple Documentation</a>.</span><br /></div>]]></content:encoded></item><item><title><![CDATA[Text Color: Animating color change and making the color change relative to other variable]]></title><link><![CDATA[https://www.absoluteripple.com/resources/text-color-animating-color-change-and-making-the-color-change-relative-to-other-variable]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/text-color-animating-color-change-and-making-the-color-change-relative-to-other-variable#comments]]></comments><pubDate>Sat, 06 Jul 2013 13:57:38 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/text-color-animating-color-change-and-making-the-color-change-relative-to-other-variable</guid><description><![CDATA[In case the title is a bit unclear, this post is about two things:1. Outline a few ways in which the color of UILabel can be changed gradually from one color to another color over a fixed period of time. The examples below will change the color from Red to Blue over 5 seconds.2. Describe an approach to make the color varied in response to the value of another variable. Method 1:  Using the animation method of UIViewA very simple approach is to use the transitionWithView:duration:option:animation [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">In case the title is a bit unclear, this post is about two things:<br /><span></span>1. Outline a few ways in which the color of <font color="#3a96b8">UILabel</font> can be changed gradually from one color to another color over a fixed period of time. The examples below will change the color from <font color="#fb0000">Red</font> to <font color="#010bf9">Blue</font> over 5 seconds.<br /><span>2. </span>Describe an approach to make the color varied in response to the value of another variable. <br /><br /><strong>Method 1:  Using the animation method of UIView</strong><br />A very simple approach is to use the <font color="#3a96b8">transitionWithView:duration:option:animations </font>method of <font color="#3a96b8">UIView</font>.<br /><span>The following assumes you have a <font color="#3a96b8">UILabel</font> called 'textLabel' in your storyboard and that you have established an </span>IBOutlet to it. That is, somewhere in your @interface file there should be a line saying something like: <br /><span></span>&nbsp;&nbsp;&nbsp; <font color="#5fa233">@property (weak, nonatomic) IBOutlet UILabel *textLabel;</font><br /><span></span>(The best way to make sure this is all link up properly is to use the control-drag approach.)<br /><span></span><br /><span></span>Then you simply add this to viewDidLoad:<br />&nbsp;&nbsp;&nbsp; <font color="#5fa233">[self.textLabel setTextColor:[UIColor redColor]];</font><br /><span></span><br /><span></span>And add the following code to viewDidAppear:<br />&nbsp;&nbsp;&nbsp; <font color="#5fa233">[UIView transitionWithView:self.textLabel<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; duration:5.0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; options:UIViewAnimationOptionTransitionCrossDissolve<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; animations:^{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [self.textLabel setTextColor:[UIColor blueColor]];<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <font color="#5fa233">}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; completion:nil];</font><br />This is it.<br /><span></span><br /><span></span><strong>Method 2: Using Core Animation CATextLayer</strong><br /><span></span>A more complex approach is to use Core Animation CATextLayer.<br /><span></span>First, add the QuartzCore framework and then #import it by adding the following to the top of your file (in either the .h or .m)<br /><span></span>&nbsp;&nbsp;&nbsp; <font color="#5fa233">#import &lt;QuartzCore/QuartzCore.h&gt;</font><br /><span></span>Next, add the following method:<br /><span></span>&nbsp;&nbsp;&nbsp; <font color="#5fa233">- (void)animateTextLayer<br /></font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">{<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">CGFloat animationDuration = 5.0;<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">CATextLayer *textLayer = [CATextLayer layer];<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">[textLayer setString:@"Foo"];<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">[textLayer setForegroundColor:[UIColor redColor].CGColor];<br />&nbsp;&nbsp;&nbsp;</font>&nbsp;&nbsp;&nbsp;&nbsp;<font color="#5fa233"> [textLayer setFontSize:50];<br />&nbsp;</font>&nbsp;&nbsp;&nbsp;&nbsp;<font color="#5fa233">&nbsp;&nbsp; [textLayer setFrame:CGRectMake(100, 150, 100, 60)];<br />&nbsp;&nbsp;&nbsp;</font>&nbsp;&nbsp;&nbsp;&nbsp;<font color="#5fa233"> [[self.view layer] addSublayer:textLayer];<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;</font>&nbsp;&nbsp;&nbsp;&nbsp;<font color="#5fa233"> CABasicAnimation *colorAnimation = [CABasicAnimation<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; animationWithKeyPath:@"foregroundColor"];<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.duration = animationDuration;<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.fillMode = kCAFillModeForwards;<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.removedOnCompletion = NO;<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.fromValue = (id)[UIColor redColor].CGColor;<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.toValue = (id)[UIColor blueColor].CGColor;<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">colorAnimation.timingFunction = [CAMediaTimingFunction<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; functionWithName:kCAMediaTimingFunctionLinear];<br />&nbsp;&nbsp;&nbsp; </font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">[textLayer addAnimation:colorAnimation<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; forKey:@"colorAnimation"];<br /><span></span></font>&nbsp;&nbsp;&nbsp; <font color="#5fa233">}</font><br />Finally, call this method in viewDidLoad:<br />&nbsp;&nbsp;&nbsp; <font color="#5fa233"><span>[self animateTextLayer];</span></font><br /><br /></div>  <div class="paragraph" style="text-align:left;"><strong>Method 3: Using NSTimer and Computing the color</strong><br />The following assumes that the UILabel has been created as described in Method 1 above.<span></span><br /><span></span>First, create a variable p by adding this under @implementation:<br /><font color="#5fa233">{<br />&nbsp;&nbsp;&nbsp; CGFloat p;<br />}</font><br /><span></span><br /><span></span>Next, add the following methods:<br /><font color="#5fa233">- (UIColor *)createColorWithColorOne:(UIColor *)colorOne ColorTwo:(UIColor *)colorTwo andProportion:(CGFloat)proportion<br />{<br />&nbsp;&nbsp;&nbsp; CGFloat colorOneRed, colorOneGreen, colorOneBlue, colorOneAlpha;<br />&nbsp;&nbsp;&nbsp; [colorOne getRed:&amp;colorOneRed green:&amp;colorOneGreen blue:&amp;colorOneBlue alpha:&amp;colorOneAlpha];<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; CGFloat colorTwoRed, colorTwoGreen, colorTwoBlue, colorTwoAlpha;<br />&nbsp;&nbsp;&nbsp; [colorTwo getRed:&amp;colorTwoRed green:&amp;colorTwoGreen blue:&amp;colorTwoBlue alpha:&amp;colorTwoAlpha];<br /><span></span>&nbsp; <br />&nbsp;&nbsp;&nbsp; CGFloat newRed = colorOneRed + (colorTwoRed - colorOneRed) * proportion;<br />&nbsp;&nbsp;&nbsp; CGFloat newGreen = colorOneGreen + (colorTwoGreen - colorOneGreen) * proportion;<br />&nbsp;&nbsp;&nbsp; CGFloat newBlue = colorOneBlue + (colorTwoBlue - colorOneBlue) * proportion;<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; return [UIColor colorWithRed:newRed green:newGreen blue:newBlue alpha:1.0];&nbsp;&nbsp; // assuming alpha is constant<br />}<br /><br />- (void)changeColor:(NSTimer *)timer<br />{<br />&nbsp;&nbsp;&nbsp; self.textLabel.textColor = [self createColorWithColorOne:[UIColor redColor]<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ColorTwo:[UIColor blueColor]<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; andProportion:p];<br />&nbsp;&nbsp;&nbsp; p +=0.1;<br />&nbsp;&nbsp;&nbsp; if (p &gt;= 1.0) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [timer invalidate];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; timer = nil;<br />&nbsp;&nbsp;&nbsp; }<br />}<br /></font><br /><span>And in viewDidLoad add:</span><br />&nbsp;&nbsp;&nbsp; <font color="#5fa233">p = 0;<br />&nbsp;&nbsp;&nbsp; NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; target:self<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; selector:@selector(changeColor:)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; userInfo:nil<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; repeats:YES];</font><br /><br /><span></span>As said above, this changes the color of the label from red to blue in 5 seconds. You can customise the duration and the smoothness of the color transition by altering the TimeInterval of the NSTimer and the increment amount for the variable p in the changeColor: method.<br /><span></span><br /><strong><span>Making the color vary with reference to another variable</span></strong><br /><span></span><br /><span>A quick word about the</span> method (UIColor *)createColorWithColorOne:(UIColor *)colorOne ColorTwo:(UIColor *)colorTwo andProportion:(CGFloat)proportion. The logic behind it is based on the equation of a line in 3D space. One way to express a color is by reference to its three color components: red, green and blue. These three values can be represented by a point in 3D space. Given two colors we have two points. And with two points we can construct a line, which can be expressed in the form of a parametric equation (this is essentially what the newRed, newGreen, newBlue lines above come down to). A feature of a parametric equation that is most useful here is that it allows us to express the coordinates by reference to another variable, that is, the variable called 'proportion' here. So by changing this vale we can get different color values between colorOne and colorTwo. <span></span>(Note: proportion is between 0.0 and 1.0 only. When proportion = 0, the color is red; when proportion = 1.0, it is blue.)<span></span><br /><br /><span>The example here </span>simply increment the proportion gradually over a period of time so that the color animates from red to blue. This is not the only use of this method. Animating color changes between two colors over a fixed duration can be achieved using method 1 and 2, which are arguably much simpler too. The method described here allows you to generate a color that lies between two other color by reference to something else. For example, red can represents a maximum temperature and blue can represent a minimum temperature. Using this method you can get a color as the temperature varies between the minimum and maximum.<br /><br /><span>With a bit more work, the code can be modified to use more than two colors</span>, such that you can gradually transitional between a multitude of colors over a period of time or as show different colors in response to changes in some other variable.<br /><span></span><br /></div>]]></content:encoded></item><item><title><![CDATA[Customising Activity View Controller - Mail]]></title><link><![CDATA[https://www.absoluteripple.com/resources/customising-activity-view-controller-mail]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/customising-activity-view-controller-mail#comments]]></comments><pubDate>Sat, 22 Jun 2013 00:32:23 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/customising-activity-view-controller-mail</guid><description><![CDATA[The previous post shows how to customize the Activity View Controller using UIActivityItemProvider, which enables you to customize the text that get shown in Twitter, Facebook, Weibo, Mail, etc. Indeed, you can customize more than just text.One thing you may notice is that with Mail, any text object that you pass to the standard Mail activity just get shown in the body of the email. How do you set the subject? Add an attachment? Set the recipient?&nbsp;You can set all this using a custom UIActiv [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">The <a href="http://www.absoluteripple.com/1/post/2013/05/customising-the-activity-view-controller.html" target="_blank" title="">previous post</a> shows how to customize the Activity View Controller using <font color="#3a96b8">UIActivityItemProvider</font>, which enables you to customize the text that get shown in Twitter, Facebook, Weibo, Mail, etc. Indeed, you can customize more than just text.<br /><br />One thing you may notice is that with Mail, any text object that you pass to the standard Mail activity just get shown in the body of the email. How do you set the subject? Add an attachment? Set the recipient?&nbsp;<br />You can set all this using a custom <a title="" target="_blank" href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivity_Class/Reference/Reference.html">UIActivity</a> together with a <a title="" target="_blank" href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemProvider_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityItemProvider">UIActivityItemProvider</a> object.<br /><br /><font color="#626262"><strong>Step 1: Start with the Previous Example</strong></font><br />This example builds upon the <a href="http://www.absoluteripple.com/1/post/2013/05/customising-the-activity-view-controller.html" target="_blank" title="">previous example about Customising Activity View Controller</a>.<br /><br /><strong><font color="#626262">Step 2: Create another subclass of UIActivityItemProvider</font></strong><br />As said in the <a href="http://Go to link: http://www.absoluteripple.com/1/post/2013/05/customising-the-activity-view-controller.html" target="_blank">previous post</a>, the object of this class serves as a proxy for data object that is passed to the activity view controller through the activityItems array. In this example, we are creating a class called <font color="#a85f2e">MailItemProvider</font>, which will generate the components (i.e. email body, subject, etc) required to populate the email message. Because the <a title="" target="_blank" href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemProvider_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityItemProvider">UIActivityItemProvider</a> object can only return a single object, all these components are put within a single object - a <font color="#3a96b8">NSDictionary</font>, which seems to be the most logical object to use for this purpose. (It appears, as of writing, that you cannot use NSArray as it is not one of the supported object type for this purpose.)<br /><br />Insert the following codes in the viewController.m file (somewhere after the #import):<br /><font color="#6cb83a">@interface MailItemProvider:UIActivityItemProvider<br /><span style=""></span> @property (nonatomic, strong) NSString *someText;<br /><span style=""></span> @end<br /><span style=""></span><span style=""></span> <span style=""></span><br /><span style=""></span> @implementation MailItemProvider<br /><span style=""></span> @synthesize someText = _someText;<br /><span style=""></span> - (id)initWithPlaceholderItem:(id)placeholderItem<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return [super initWithPlaceholderItem:placeholderItem];<br /><span style=""></span>}<br /><br /><span style=""></span> - (id)item<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return [NSDictionary dictionary];<br /><span style=""></span> }<br /><span style=""></span> -(id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; NSDictionary *exportDetailsDict = [NSDictionary dictionary];<br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:kYourCustomMailType]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; //-- create the attachment data<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSData *attachementData = [NSData data];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; //-- message for the email<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theMessage = [NSString stringWithFormat:@"Some message:\n%@",_someText];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; //-- subject for the email<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theSubject = @"Email Subject";<br />&nbsp; &nbsp; &nbsp; &nbsp;//-- create the dictionary<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; exportDetailsDict = [NSDictionary dictionaryWithObjectsAndKeys:attachementData,@"ATTACHMENT",<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theMessage,@"MESSAGE",<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theSubject,@"SUBJECT", nil];<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span> &nbsp; &nbsp; return exportDetailsDict;<br /><span style=""></span> }<br /><br /><span style=""></span> - (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return [NSDictionary dictionary];<br /><span style=""></span> }<br /><span style=""></span> @end<br /></font><br />In addition to the above, you also need to define a NSString constant. Insert the following after the last #import line:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<font color="#6cb83a">NSString *const kYourCustomMailType = @"YourCustomMailType";</font><br /><br />The above codes follow the same logic as the previous post about using UIActivityItemProvider. Instead of returning a <font color="#3a96b8">NSString</font> object, the above return a <font color="#3a96b8">NSDictionary</font>.<br /><br />This example only generates the body of the email message, the subject text and an attachment (which is just an empty pdf container here). You can of course populate the to, cc, and bcc recipient fields in your code as well.<br /><br /><font color="#626262"><strong>Step 3: Create a custom UIActivity</strong></font><br />Next, you need to roll your own <a title="" target="_blank" href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityViewController">UIActivity</a>. We will create <font color="#a85f2e">MailExportActivity</font> which is a subclass of <a title="" target="_blank" href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityViewController"><font color="#3a96b8">UIActivity</font></a>. This class will handle your custom type (called '<font color="#a85f2e">YourCustomMailType</font>' in this example) and present the standard mail interface using the <font color="#3a96b8">MFMailComposerViewController</font>. Unlike the standard Mail activity, our custom activity will allow you to pre-populate the various components of the email.<br /><br />First, include the <font color="#3a96b8">MessageUI</font> framework, and <font color="#6cb83a">#import &lt;MessageUI/MessageUI.h&gt;</font><br /><br />Next, insert the following codes in the viewController.m file:<br /><br /><font color="#6cb83a">@interface MailExportActivity : UIActivity&nbsp; &lt;MFMailComposeViewControllerDelegate&gt;<br /><span style=""></span> @property (nonatomic, strong) NSArray *items;<br /><span style=""></span> @end</font><br /><br /><font color="#6cb83a"> @implementation MailExportActivity<br /><span style=""></span> @synthesize items = _items;<br /><br /><span style=""></span> - (NSString *)activityType<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return kYourCustomMailType;<br /><span style=""></span> }<br /><br /><span style=""></span> - (NSString *) activityTitle<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return @"Custom Mail";<br /><span style=""></span> }<br /><br /><span style=""></span> - (UIImage *) activityImage<br /><span style=""></span> {</font><br /><font color="#6cb83a">&nbsp; &nbsp; //This creates an UIImage with the word 'mail' in the middle.</font><br /><font color="#6cb83a">&nbsp; &nbsp; //Alternatively, you can use [UIImage imageNamed: ] to create the UIImage object</font><br /><font color="#6cb83a"><br /><span style=""></span> &nbsp; &nbsp; CGRect rect = CGRectMake(0.0f, 0.0f, 85.0f, 85.0f);<br /><span style=""></span> &nbsp; &nbsp; UIGraphicsBeginImageContext(rect.size);</font><br /><font color="#6cb83a"><br /><span style=""></span> &nbsp; &nbsp; rect = CGRectInset(rect, 15.0f, 15.0f);<br /><span style=""></span> &nbsp; &nbsp; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10.0f];<br /><span style=""></span> &nbsp; &nbsp; [path stroke];</font><br /><font color="#6cb83a"><br /><span style=""></span> &nbsp; &nbsp; rect = CGRectInset(rect, 0.0f, 10.0f);<br /><span style=""></span> &nbsp; &nbsp; [@"Mail" drawInRect:rect withFont:[UIFont fontWithName:@"Futura" size:13.0f] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];<br /><br /><span style=""></span> &nbsp; &nbsp; UIImage *image = UIGraphicsGetImageFromCurrentImageContext();<br /><span style=""></span> &nbsp; &nbsp; UIGraphicsEndImageContext();<br /><br /><span style=""></span> &nbsp; &nbsp; return image;<br /><span style=""></span> }<br /><br /><span style=""></span> - (BOOL)canPerformWithActivityItems:(NSArray *)activityItems<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; //Determine whether this service should be displayed by the UIActivityController<br /><span style=""></span> &nbsp; &nbsp; //(This mostly depends if this service can do something with the objects/ data provided via the activityItems<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; for (id item in activityItems){<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; if ([item isKindOfClass:[NSDictionary class]]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return YES;<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; }<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span> &nbsp; &nbsp; return NO;<br /><span style=""></span> }<br /><br /><span style=""></span> - (void)prepareWithActivityItems:(NSArray *)activityItems<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; //This gets call when the user select this custom service<br /><span style=""></span> &nbsp; &nbsp; //Then, the controller will either call :<br /><span style=""></span> &nbsp; &nbsp; //(a) the activityViewController, or<br /><span style=""></span> &nbsp; &nbsp; //(b) performActivity.<br /><br /><span style=""></span> &nbsp; &nbsp; self.items = activityItems;<br /><span style=""></span> }<br /><br /><span style=""></span> - (UIViewController *) activityViewController<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; //-- codes to generate the export data<br /><span style=""></span> &nbsp; &nbsp; NSString *theSubject = @"Default Subject";<br /><span style=""></span> &nbsp; &nbsp; NSString *theMessage = @"Default Message";<br /><span style=""></span> &nbsp; &nbsp; NSString *theFileName = @"default.pdf";<br /><span style=""></span> &nbsp; &nbsp; NSData *theData;<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; for (id eachItem in _items){<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; if ([eachItem isKindOfClass:[NSDictionary class]]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NSDictionary *exportDetailsDict = eachItem;<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theSubject = [exportDetailsDict objectForKey:@"SUBJECT"];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theMessage = [exportDetailsDict objectForKey:@"MESSAGE"];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theData = [exportDetailsDict objectForKey:@"ATTACHMENT"];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; }<br /><span style=""></span> &nbsp; &nbsp; }<br /><br /><span style=""></span> &nbsp; &nbsp; MFMailComposeViewController *mailComposeVC = [[MFMailComposeViewController alloc] init];<br /><span style=""></span> &nbsp; &nbsp; mailComposeVC.mailComposeDelegate = self;<br /><span style=""></span> &nbsp; &nbsp; [mailComposeVC setSubject:theSubject];<br /><span style=""></span> &nbsp; &nbsp; //[mailComposeVC setToRecipients:[[NSArray alloc] initWithObjects:@"info@example.com", nil]];<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; [mailComposeVC setMessageBody:theMessage isHTML:NO];<br /><br /><span style=""></span> &nbsp; &nbsp; [mailComposeVC addAttachmentData:theData<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mimeType:@"application/pdf"<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fileName:theFileName];<br /><br /><span style=""></span> &nbsp; &nbsp; return mailComposeVC;<br /><span style=""></span> }<br /><br /><span style=""></span> #pragma martk - MFMailComposeViewControllerDelegate<br /><span style=""></span> - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; if (result == MFMailComposeResultSent) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; //This notifies the system that your activity object has completed its work.<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; //This will dismiss the view controller provided via activityViewController method and the sharing interface provided by the UIActivityViewController<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; [self activityDidFinish:YES];<br /><span style=""></span> &nbsp; &nbsp; } else<br /><span style=""></span> &nbsp; &nbsp; {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; [self activityDidFinish:NO];<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span> }<br /><span style=""></span> @end</font><br /><br />Comments have been inserted above, so it is self-explaining. It is simply overriding and implementing the methods in the <font color="#3a96b8">UIActivity</font> class. If anything is not clear, it is always good to consult the Apple Documentation.<br /><br />When your custom activity icon is clicked, the <font color="#a85f2e">activityItem</font> created under step 2 above is passed to your custom class. The method&nbsp;<font color="#6cb83a">(void)prepareWithActivityItems:(NSArray *)activityItems </font>gets called. In this example, the <font color="#a85f2e">activityItem</font> object (which contains the <font color="#3387a2">NSDictionary</font>) is assigned to the <font color="#a85f2e">items</font> <font color="#3387a2">NSArray</font>.<br /><br />When you roll your own <font color="#3a96b8">UIActivity</font>, you can present a UIViewController in which the user can provide additional input before perform whatever service you want to do on the data. The UIViewController that gets presented is the one&nbsp;returned under the <font color="#6cb83a">(UIViewController *)&nbsp;activityViewController</font> method. Inside this method, we have instantiated the usual&nbsp;<font color="#3a96b8">MFMailComposeViewController</font> and populated its properties with the values and data that we have passed in through the <font color="#3a96b8">NSDictionary</font> object inside the <font color="#a85f2e">items</font> <font color="#3a96b8">NSArray</font>.<br /><br />Our custom <font color="#a85f2e">Mail</font><font color="#a85f2e">ExportActivity</font> class also confirms to the <a target="_blank" href="https://developer.apple.com/library/ios/#documentation/MessageUI/Reference/MFMailComposeViewControllerDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intf/MFMailComposeViewControllerDelegate" title="">MFMailComposeViewControllerDelegate protocol</a>. (This what the bit of the code "UIActivity&lt;MFMailComposeViewControllerDelegate&gt;" means.)&nbsp;This is important as this provides the means to inform the Activity View Controller when our custom service has performed its task (i.e. sending the email) or when user otherwise cancel the task (such as clicking the 'cancel' button in the MFMailComposeView). When this happens, the delegate method  <font color="#6cb83a">(void)mailComposeController:(MFMailComposeViewController *)controller  didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error </font>gets called. Inside this method we invoke the <font color="#6cb83a">activityDidFinish:(BOOL)completed</font> method of <font color="#3387a2">UIActivity</font> class. This dismisses the view controller presented by the UIActivityViewController as well as the MFMailComposeView.<br /><br /><font color="#626262"><strong>Step 4: Instantiate Your custom UIActivityItemProvider and the Your Custom UIActivity</strong></font><br />Delete the <font color="#a85f2e">activityItems</font> <font color="#3387a2">NSArray</font> and the instantiation of the UIActivityViewController under the previous post. Then insert the following:&nbsp;<br /><br />&nbsp; &nbsp; <font color="#6cb83a">MailItemProvider *mailItem = [[MailItemProvider alloc] initWithPlaceholderItem:[NSDictionary dictionary]];<br /><span style=""></span> &nbsp; &nbsp; mailItem.someText = _aTextView.text;<br /><br /><span style=""></span> &nbsp; &nbsp; //--- initialise the custome activity<br /><span style=""></span> &nbsp; &nbsp; UIActivity *customMailActivity = [[MailExportActivity alloc] init];<br /><span style=""></span> &nbsp; &nbsp; NSArray *activityItems = [NSArray arrayWithObjects:textItem, mailItem, nil];<br /><br /><span style=""></span> &nbsp; &nbsp; //-- initialising the activity view controller (with custom activity)<br /><span style=""></span> &nbsp; &nbsp; UIActivityViewController *avc = [[UIActivityViewController alloc]<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; initWithActivityItems:activityItems<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; applicationActivities:@[customMailActivity]];</font><br /><br /></div>  <span class='imgPusher' style='float:left;height:0px'></span><span style='z-index:10;position:relative;float:left;;clear:left;margin-top:0px;*margin-top:0px'><a><img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/8005429.jpg" style="margin-top: 5px; margin-bottom: 10px; margin-left: 0px; margin-right: 10px; border-width:1px;padding:3px;" alt="Picture" class="galleryImageBorder" /></a><span style="display: block; font-size: 90%; margin-top: -10px; margin-bottom: 10px; text-align: center;"></span></span> <div class="paragraph" style="text-align:left;display:block;">The UIActivityView screen should now contain a custom icon like that shown on the left hand side image. When you clicked it the email view will appear with a subject text, a body text and an attachment. (As said above, the attachment in this example is just a dummy attachment, and you can also populate other email fields by extending the approach described here. Essentially, you just need to add a few more key value pairs to the NSDictionary object.)</div> <hr style="width:100%;clear:both;visibility:hidden;"></hr>  <div class="paragraph" style="text-align:left;">In your code it would be a good idea to determine if mail capabilities are enabled on the user's device first before initialising the above activity view controller with your custom activity (which would present a mail controller). You can do this by using:<br />&nbsp; &nbsp; &nbsp; &nbsp; <font color="#6cb83a">[MFMailComposeViewController canSendMail]</font><br />If this returns true, you can initialise the above activity view controller; if false, you can initialise the plain vanilla activity view controller without the custom activity.</div>]]></content:encoded></item><item><title><![CDATA[Customising the Activity View Controller]]></title><link><![CDATA[https://www.absoluteripple.com/resources/customising-the-activity-view-controller]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/customising-the-activity-view-controller#comments]]></comments><pubDate>Mon, 27 May 2013 10:47:40 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/customising-the-activity-view-controller</guid><description><![CDATA[The UIActivityViewController class provides a quick and simple way to add common actions to an app, such as post to Facebook, post to Twitter, send a mail or message, copy to pasteboard, etc. It is nice and simple when you are dealing with invariant data, such as when you want to send the same message across Facebook, Twitter, Weibo and mail. You can do that using the approach outlined in a previous post. However, there are many occasions where you probably want to do things differently dependin [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">The <font color="#3a96b8">UIActivityViewController</font> class provides a quick and simple way to add common actions to an app, such as post to Facebook, post to Twitter, send a mail or message, copy to pasteboard, etc. It is nice and simple when you are dealing with invariant data, such as when you want to send the same message across Facebook, Twitter, Weibo and mail. You can do that using the approach outlined in <a href="http://www.absoluteripple.com/1/post/2012/10/activity-view-controller.html" target="_blank" title="">a previous post</a>. <br /><span></span><br />However, there are many occasions where you probably want to do things differently depending on the service. For example, you may want to send a particular message when posting to Facebook and a different one when posting to Twitter. The character limit on Twitter may mean, for example, that you want to truncate the message that you post to Twitter. You may want to have a different image resolution for different things.<br /><span></span><br />How do you do this? This post describes one approach to achieve this - using the <a href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemProvider_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityItemProvider" target="_blank" title="">UIActivityItemProvider</a> class.<br />This class uses the call back defined in the&nbsp;<a href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemSource_protocol/Reference/Reference.html#//apple_ref/occ/intf/UIActivityItemSource" target="_blank" title="" style="">UIActivityItemSource protocol</a>&nbsp;to enable you to vary the data depending on activity type.<br /><br /><strong><font color="#626262">Step 1: Start with the Previous Example</font></strong><br />This example builds upon the example in <a href="http://www.absoluteripple.com/1/post/2012/10/activity-view-controller.html" title="">the previous post</a>.&nbsp;<br /><br /><strong><font color="#626262">Step 2: Creates a &nbsp;Subclass of the UIActivityItemProvider Class</font></strong><br />Add the following code to the ViewController.m file:<br /><br /><font color="#6cb83a">@interface TextItemProvider:UIActivityItemProvider<br /><span style=""></span> @property (nonatomic, strong) NSString *someText;<br /><span style=""></span> @end</font><br /><span style=""></span><span style=""></span> <span style=""></span><br /><span style=""></span><font color="#6cb83a"> @implementation TextItemProvider<br /><span style=""></span> @synthesize someText = _someText;<br /><span style=""></span> - (id)initWithPlaceholderItem:(id)placeholderItem<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; //Initializes and returns a provider object with the specified placeholder data<br /><span style=""></span> &nbsp; &nbsp; return [super initWithPlaceholderItem:placeholderItem];<br /><span style=""></span> }<br /><br /><span style=""></span> - (id)item<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; //Generates and returns the actual data object<br /><span style=""></span> &nbsp; &nbsp; return @"";<br /><span style=""></span> }<br /><br /><span style=""></span> // The following are two methods in the UIActivityItemSource Protocol<br /><span style=""></span> // (UIActivityItemProvider conforms to this protocol) - both methods required<br /><br /><span style=""></span> //- Returns the data object to be acted upon. (required)<br /><span style=""></span> - (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:UIActivityTypePostToFacebook]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theText = @"Some text for Facebook";<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; return theText;<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:UIActivityTypePostToTwitter]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theText = @"Some text for Twitter";<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; return theText;<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:UIActivityTypePostToWeibo]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theText = @"Some text for Weibo";<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; return theText;<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:UIActivityTypeMail]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theText = _someText;<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; return theText;<br /><span style=""></span> &nbsp; &nbsp; }<br /><span style=""></span><br /><span style=""></span> &nbsp; &nbsp; if ([activityType isEqualToString:kYourCustomMailType]) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *theText = @"Some text for your Custom Type";<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; return theText;<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; }<br /><br /><span style=""></span> &nbsp; &nbsp; return @"Some default text";<br /><span style=""></span> }<br /><br /><span style=""></span> //- Returns the placeholder object for the data. (required)<br /><span style=""></span> //- The class of this object must match the class of the object you return from the above method<br /><span style=""></span> - (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController<br /><span style=""></span> {<br /><span style=""></span> &nbsp; &nbsp; return @"";<br /><span style=""></span> }<br /><span style=""></span> @end</font><br /><span style=""></span><br /><span style=""></span><br />The above creates a class called TextItemProvider, which is a subclass of the <font color="#3a96b8"><a href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemProvider_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityItemProvider" target="_blank" title="">UIActivityItemProvider</a></font>. For convenience here, the code is put in the ViewController.m file. You may want to put this in a separate file and #import it.<br /><br />The comments inserted into the code above should provide a good idea of how it works.&nbsp;<br /><br />Essentially, object of this class serves as a proxy for the eventual data/ object that get passed to the Activity View Controller. According to the documentation it is a type of operation (NSOperation) that enables you to delay passing data. As it runs asynchronously (i.e. not in the main thread) it can be used to process large data (e.g. video files) without disrupting the user experience. &nbsp;<br /><br />The most important method to achieve our goal here is the method:<br /><font color="#6cb83a">(id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType</font><br /><br /><span></span>This method is defined in the <a href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityItemSource_protocol/Reference/Reference.html#//apple_ref/occ/intf/UIActivityItemSource" target="_blank" title="">UIActivityItemSource protocol</a> (the UIActivityItemProvider class conforms to this protocol). When the user clicks the service in the activity view controller screen, this method is called and it returns the data object, which is a NSString object in this case (but it can be other objects). In this example, the codes simply generate a different text depending on the <font color="#3a96b8">activityType</font>. &nbsp;<br /><br /><font color="#626262"><strong>Step 3: Create the UIActivityItemProvider object and add it to the Activity View Controller</strong></font><br />Delete the line in the previous example that says:<br />&nbsp; &nbsp; &nbsp; &nbsp; <font color="#6cb83a">NSArray *activityItems = [NSArray arrayWithObjects:textObject, url, image, nil];</font><br /><span style=""></span>(You can also delete the NSString, NSURL, UIImage lines above it too if you like, but leaving it should not harm this example.)<br /><br />And replace it with the following:<br />&nbsp; &nbsp; &nbsp; &nbsp; <font color="#6cb83a">TextItemProvider *textItem = [[TextItemProvider alloc] initWithPlaceholderItem:@"Default text"];<br />&nbsp; &nbsp; &nbsp; &nbsp; textItem.someText = _aTextView.text;<br />&nbsp; &nbsp; &nbsp; &nbsp; NSArray *activityItems = [NSArray arrayWithObjects:textItem, nil];</font><br /><span style=""></span><br /><span style=""></span>This creates a TextItemProvider object called textItem. The next line simply passes the text in aTextView to the textItem object so that it can use the text (if required) when it generates the NSString data. You can pass other data or variables to it if required by your app.<br /><br />When the activity view controller is instantiated (see previous code), the textItem object will be one of the Activity Item.&nbsp;<br /><br />The result is that when you clicked the Twitter icon in the Activity View screen, the Twitter screen will contain the text "Some text for Twitter". If you click the Facebook icon, it will be "Some text for Facebook", and so on.<br /><br /></div>]]></content:encoded></item><item><title><![CDATA[Using AFNetworking]]></title><link><![CDATA[https://www.absoluteripple.com/resources/using-afnetworking]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/using-afnetworking#comments]]></comments><pubDate>Mon, 28 Jan 2013 07:11:31 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/using-afnetworking</guid><description><![CDATA[In the past I have been using ASIHTTPRequest networking library for my apps. It was simple to use which is a good thing for someone who was new to iOS programming. I only needed it for simple GET/POST requests, returning the occasional JSON. A few simple example codes that I found at that time also make picking up ASIHTTPRequest nice and easy. Unfortunately, I soon I realized that the developer is no longer updating the library. I resisted changing to another networking library for a long while, [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">In the past I have been using <a title="" target="_blank" href="http://allseeing-i.com/ASIHTTPRequest/">ASIHTTPRequest</a> networking library for my apps. It was simple to use which is a good thing for someone who was new to iOS programming. I only needed it for simple GET/POST requests, returning the occasional JSON. A few simple example codes that I found at that time also make picking up ASIHTTPRequest nice and easy.<span> Unfortunately, I soon I realized that the developer is no longer updating the library. I resisted changing to another networking library for a long while, because I don't feel like learning another library and </span>because there don't seen to be much simple example codes around. Codes that were available (or at least those that I can find) are either too brief or dealt with things I don't need, and the codes also look rather complex when compared to those in the ASIHTTPRequest library. In short, it seems complicated and takes a lot of time to learn - and I don't have the time.<br /><br /><span>Recently, I have found time to look into <a title="" target="_blank" href="https://github.com/AFNetworking/AFNetworking">AFNetworking</a> a bit more</span> and it is also time to change to another networking library as it would be most unwise to keep using a library that has ceased to be developed since mid 2011.&nbsp;ASIHTTPRequest still seems to work fine for the occasional, light networking uses that I need it for.<br /><br /><span></span>AFNetworking turns out to be much simpler than I had initially expected. It is also much more powerful, flexible and maintainable going forward. The main reason for this is that it is built on top of NSURLConnection and NSOperation, and it uses blocks which is also the reason that it looks much more complex when I first looked at it (at which time my understanding of blocks is next to nil and hardly know anything about NSURLConnection or NSOperation). <br /><br /><span></span>AFNetworking has <a href="http://afnetworking.github.com/AFNetworking/" target="_blank">good documentation,</a> but there there seems very little example around. And I prefer to learn by going through an example, especially short codes that illustrate the basic principle or approach. In particular, I was puzzled by how to make a simple HTTP GET or POST request using AFNetworking. Here are some simple codes snippet and notes.<br /><br /><span></span><strong>Set Up your Project to Use AFNetworking</strong><br /><br /><span>The <a title="" target="_blank" href="https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking">Getting Started guide </a>on AFNetworking github page is most useful for this purpose. </span><br /><br /><span></span><strong>HTTP GET Request</strong><br /><br /><span>You need to </span>use the AFHTTPClient and AFHTTPRequestOperation, so import them as follows :<br /><span></span><br /><font color="#33CC00">#import "AFHTTPClient.h"<br />#import "AFHTTPRequestOperation.h<span></span>"</font><br /><br /><span></span><em>The codes:</em><br /><font color="#33CC00">AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://</font><font color="#3366ff">yourServerAddress.com</font><font color="#33CC00">/"]];<br />&nbsp;&nbsp;&nbsp; [httpClient setParameterEncoding:AFFormURLParameterEncoding];<br />&nbsp;&nbsp;&nbsp; NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; path:@"</font><font color="#3366ff">http://yourServerAddress.com/example?name=foo</font><font color="#33CC00">"<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; parameters:nil];<br /><span></span><br /><span></span>[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];<br />&nbsp;&nbsp;&nbsp; AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; success:^(AFHTTPRequestOperation *operation, id responseObject) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </font><font color="#999999">//-- This block gets invoked when the operation is successful</font><br /><font color="#999999">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //-- Here it simply print out the responseObject as text in the log</font><br /><font color="#33cc00">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);</font><br /><font color="#33cc00">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } failure:^(AFHTTPRequestOperation *operation, NSError *error) {</font><br /><font color="#33CC00">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</font><font color="#999999">//-- This block gets invoked when the operation fails</font><font color="#33CC00"><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Error: %@", error.localizedDescription);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }];</font><br /><font color="#999999">//-- The following codes allow you to track the download progress (if required)</font><br /><font color="#33cc00">[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {</font><br /><font color="#33cc00">&nbsp; &nbsp; &nbsp; &nbsp; </font><font color="#999999">//-- This block gets invoked periodically as the download progress</font><br /><font color="#33cc00"><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"bytesRead: %i; totalBytesRead: %lld; totalexpected: %lld", bytesRead, totalBytesRead, totalBytesExpectedToRead);</font><br /><font color="#33cc00"><span style=""></span> &nbsp; &nbsp; }];</font><br /><span style=""></span><br /><font color="#999999">//-- end of the download progress tracking code</font><br /><font color="#33CC00"><br /><span></span>[httpClient enqueueHTTPRequestOperation:operation];</font><br /><br /><em>Alternative codes:</em><br />(using the getPath: method in AFHTTPClient)<br /><span style="color: rgb(51, 204, 0); ">AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://</span><font color="#3366ff">yourServerAddress.com</font><font color="#33cc00">/"]];</font><br /><font color="#33cc00">NSString *pathStr = @"</font><span style="color: rgb(51, 102, 255); ">/example?name=foo</span><span style="color: rgb(51, 204, 0); ">";</span><br /><font color="#33cc00"><span style=""></span>[httpClient getPath:pathStr parameters:paramaters success:^(AFHTTPRequestOperation *operation, id responseObject) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Request Successful, response '%@'", responseStr);<br /><span style=""></span> &nbsp; &nbsp; } failure:^(AFHTTPRequestOperation *operation, NSError *error) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Error: %@", error.localizedDescription);<br /><span style=""></span> &nbsp; &nbsp; }];<br /></font><span style=""></span><br />The alternative is shorter, but the first version is more customisable. In particular, it allows you to get a reference to the relevant&nbsp;AFHTTPRequestOperation.<br /><br /><strong style="">HTTP POST Request</strong><br /><br />Likewise, you need to&nbsp;use the AFHTTPClient and AFHTTPRequestOperation, so import them as noted above.<br /><br /><em style="">The codes:</em><br /><span style=""></span><font color="#33cc00">AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://</font><span style="color: rgb(51, 102, 255); ">yourServerAddress.com</span><span style="color: rgb(51, 204, 0); ">/"]];</span><br /><font color="#999999">//-- the content of the POST request is passed in as an NSDictionary</font><br /><font color="#999999">//-- in this example, there are two keys with an object each</font><br /><font color="#33cc00">NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </font><font color="#3366ff">object1</font><font color="#33cc00">, @"</font><font color="#3366ff">KEY_NAME_1</font><font color="#33cc00">",<br /><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </font><font color="#3366ff">object2</font><font color="#33cc00">, @"</font><font color="#3366ff">KEY_NAME_2</font><span style="color: rgb(51, 204, 0); ">",</span><br /><font color="#33cc00"><span style=""></span> &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nil];</font><br /><span style=""></span><br /><font color="#33cc00">[httpClient postPath:@"/</font><font color="#3366ff">postExample</font><font color="#33cc00">/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Request Successful, response '%@'", responseStr);<br /><span style=""></span> &nbsp; &nbsp; } failure:^(AFHTTPRequestOperation *operation, NSError *error) {<br /><span style=""></span> &nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Error: %@", error.localizedDescription);<br /><span style=""></span> &nbsp; &nbsp; }];<br /></font><span style=""></span><span style=""></span><span style=""></span><br /><strong>Subclassing AFHTTPClient</strong><br />The above codes use an instance of the AFHTTPClient class. The <a href="http://afnetworking.github.com/AFNetworking/Classes/AFHTTPClient.html" target="_blank">documentation for AFNetworking</a>, however, suggests that we should sub-class it for each website or web application that the app communicates with.&nbsp;<br /><br /></div>]]></content:encoded></item><item><title><![CDATA[Apple In-App Purchase: Creating App Store Hosted Content]]></title><link><![CDATA[https://www.absoluteripple.com/resources/apple-in-app-purchase-creating-app-store-hosted-content]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/apple-in-app-purchase-creating-app-store-hosted-content#comments]]></comments><pubDate>Wed, 02 Jan 2013 10:49:12 GMT</pubDate><category><![CDATA[in app purchase]]></category><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/apple-in-app-purchase-creating-app-store-hosted-content</guid><description><![CDATA[Following the introduction of iOS 6 it is possible to host the content of your in-app purchase on Apple's server, rather than having to host the contents on your own server under previous iOS versions. This makes it simpler (and perhaps less expensive) to implement in-app purchase for your app as you no longer need to develop and maintain your own server to host the purchased contents.The steps in filling out the online forms in iTunes Connect when setting up each product that you want to sell v [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">Following the introduction of iOS 6 it is possible to host the content of your in-app purchase on Apple's server, rather than having to host the contents on your own server under previous iOS versions. This makes it simpler (and perhaps less expensive) to implement in-app purchase for your app as you no longer need to develop and maintain your own server to host the purchased contents.<br /><span>The steps in filling out the online forms in iTunes Connect </span>when setting up each product that you want to sell via in-app purchase appears simple enough until you come to the point where you need to upload the content to the Apple server. How do you upload the content? What format should the content be in? There is a scarcity of documentation or guides around regarding this. Some guides simply said that your need to put all your contents in a 'package' and that is what you upload to Apple. This raises another question: what is this 'package' thing? How do you create it?<br /><span></span>After putting together information from many sources, here are the steps to create the Apple App Store hosted content and also how to upload the same to Apple.<br /><em><strong><span>What is the Package?</span></strong></em><br /><span></span>The package is simply a structured folder, which contains a <font color="#663366">ContentInfo.plist </font>in the root level and a sub-folder called 'Contents'. The <font color="#663366">ContentInfo.plist</font> contains two keys: <br /><ul><li><span><font color="#663366">ContentVersion</font> -</span> This is the version number of the content.</li><li><span><font color="#663366">IAPProductionIdentifier</font> - </span>This is the product identifier of the product with which the content is associated. i.e. the identifier you defined in iTunes Connect.</li></ul><span>The Contents folder contains the actual files associated with the in-app purchase. e.g. in an app that sell music score, it would be the actual music score file or files. Note that the content must not contain executable codes</span>, otherwise the package would not be valid.<br /><em><strong><span>How to create the Package</span></strong></em><br />Even though the package is structured folder, you <em>cannot</em> just create a folder on the Finder with the above contents. The best way to create the package that meets Apple's requiremetns it seems at the moment is to use Xcode. (The following steps are based on Xcode 4.6.)<br /><span></span><br /><em><strong><span>Creating the Package</span></strong></em><br /><span></span><strong>Step 1: Create a New Project in Xcode</strong><br /><span>File &gt; New &gt; Project</span><br />Select "Other" under iOS heading on the left hand panel of the template screen.<br /><span>Select 'In-App Purchase Content" on the right hand side.</span><br /><span>Then click "Next".</span><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/121902_orig.jpg" alt="Picture" style="width:100%;max-width:729px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong style="">Step 2: Enter the info for this project</strong><br />For Product Name, enter the product identifier as defined by you in iTunes Connect. The two must be the same. Fill in the Organization Name and Company identifier as you normally would. In this example, the identifier is "p02050".<br /><span>Then click "Next".</span><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/714081_orig.jpg" alt="Picture" style="width:100%;max-width:730px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong>Step 3: Update the ContentInfo.plist</strong><br /><span></span>Unfold the Supporting Files section of the project navigator panel and select the ContentInfo.plist file. Update the two keys in this file.<br /><span></span>ContentVersion - the default version is 1.0, update this as required<br /><span>IAPProductIdentifier - change this so that it matches the Product Identifier your defined in iTunes Connect.</span><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/7348175_orig.jpg" alt="Picture" style="width:100%;max-width:1036px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong>Step 4: Add in the Actual Contents</strong><br /><span></span>Locate all the relevant content files on your computer in the Finder.<br /><span>Drag and drop the files onto the Supporting Files section of the project navigator panel.</span><br /><span>Complete the panel as shown below and then clicked "Finish".</span><span></span><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/8998715_orig.jpg" alt="Picture" style="width:100%;max-width:727px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong>Step 5: Archive the Project</strong><br /><span></span>Select Project &gt; Archive from the menu.<br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/6577616_orig.jpg" alt="Picture" style="width:100%;max-width:1100px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong>Step 6: Validate the Package</strong><br /><span></span>Click the "Validate" button. <br /><span>Fill in the panel that appear as you normally would when validating and submitting an app.</span><span> Make sure the correct app content is selected in the In-App Purchase Content drop down menu.</span><br /><strong><span>Step 7: Export the Package</span></strong><br />Click the "Distribute" button. <br /><span></span>Select the "Export Package" radio button and click "Next".<br /><span>Enter a name and Select a location on your computer to save the resulting package.</span><br /><span>Then clicked "Save".</span><br /><span>This step is option as you can upload the content at this point using Xcode. See below.</span><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/4499719_orig.jpg" alt="Picture" style="width:100%;max-width:725px" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong><em>How to Upload the Package?</em></strong><br />You have two options:<br /><span>a. use Xcode; or</span><br /><span>b. </span>use Application Loader - This is a free tool provided by Apple. After you have logged in to iTunes Connect, clicked the "Managed Your Applications" link. The link to this Applciation Loader is located towards the bottom of the screen.<br /><span></span><strong>Using Xcode to Upload</strong><br />This is same as what you normally do when submitting an app for review. That is, instead of choosing the "Export Package" option in the above panel, choose "Submit in-app purchase content". After clicking Next, put in your developer program credentials and select the correct application and product identifier, then click "Submit"<br /><span></span><br /><span></span><br /><span></span><br /></div>]]></content:encoded></item><item><title><![CDATA[Activity View Controller]]></title><link><![CDATA[https://www.absoluteripple.com/resources/activity-view-controller]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/activity-view-controller#comments]]></comments><pubDate>Sun, 28 Oct 2012 10:45:40 GMT</pubDate><category><![CDATA[Uncategorized]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/activity-view-controller</guid><description><![CDATA[ You would have seen the familiar interface on the left if you are using iOS 6. It pops up when you click the action button in many of Apple apps and, increasingly, in many other apps. It is a quick, simple and user-friendly way to present various actions that the user can perform inside an app. It is especially a great way to provide social network integration in your apps. iOS 6 added a new UIActivityViewController class which makes creating such an interface simple. This post goes through the [...] ]]></description><content:encoded><![CDATA[<span class='imgPusher' style='float:left;height:0px'></span><span style='z-index:10;position:relative;float:left;;clear:left;margin-top:0px;*margin-top:0px'><a><img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/8948484.png?129" style="margin-top: 5px; margin-bottom: 10px; margin-left: 0px; margin-right: 10px; border-width:1px;padding:3px;" alt="Picture" class="galleryImageBorder" /></a><div style="display: block; font-size: 90%; margin-top: -10px; margin-bottom: 10px; text-align: center;"></div></span> <div class="paragraph" style="text-align:left;display:block;">You would have seen the familiar interface on the left if you are using iOS 6. It pops up when you click the action button in many of Apple apps and, increasingly, in many other apps. It is a quick, simple and user-friendly way to present various actions that the user can perform inside an app. It is especially a great way to provide social network integration in your apps. <br /><span></span>iOS 6 added a new UIActivityViewController class which makes creating such an interface simple. This post goes through the steps to implement such an interface. <br /><span>The following example creates a new app called Activity View Example</span>. <br /><strong><span>Step 1: Create a new Single View Application in xcode</span></strong><br /><span></span>In Xcode, creates a new Single View Application. You can use whatever product name you want, but I am using "ActivityViewExample" here. Fill out the usual fields. I am selecting Universal (I like to use universal when I test out some example codes as I like the flexibility to test with iPad sometimes, but this example will only look at iPhone so you can select iPhone only if you prefer). Select use Storyboards and use ARC.<br /><span>UIActivityViewController class is only available in iOS 6+. So you need to make sure that the Deployment Target of your app is 6.0+ (this should be the default setting). You can check or change it by selecting the Scode project in the Navigator and then going to the Summary tab</span>.<br /><span>For this example, I will also be showing how to make the app compatible with iOS 5 or iOS5.1 as well. Of course, for the pre-iOS 6.0 versions, the functionality offered by the UIActivityViewController class won't be available but you can always provide a simple alternative </span>so that your app still function, but with a reduced functionalities. So for this example, I have selected Deployment Target 5.0. <br /><span><em>Important: </em>if you are targeting pre-iOS 6 devices, make sure you are <strong>not</strong> using Autolayout</span> otherwise your app will crash on launch. With the Storyboard selected, go to the File Inspector and de-select the Use Autolayout option.<br /></div> <hr style="width:100%;clear:both;visibility:hidden;"></hr>  <span class='imgPusher' style='float:right;height:0px'></span><span style='z-index:10;position:relative;float:right;;clear:right;margin-top:0px;*margin-top:0px'><a><img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/7146083.png?247" style="margin-top: 5px; margin-bottom: 10px; margin-left: 10px; margin-right: 0px; none;" alt="Picture" class="galleryImageBorder" /></a><div style="display: block; font-size: 90%; margin-top: -10px; margin-bottom: 10px; text-align: center;"></div></span> <div class="paragraph" style="text-align:left;display:block;"><strong>Step 2: Setup the View in Storyboard</strong><br /><span></span>Inside the iPhone storyboard, add in a text view and a toolbar at the bottom. Put some text (whatever you want) in the text view. Change the icon on the toolbar to an Action icon. The result should be as shown on the left.<br /><span>Next, add an IBOutlet to the text view and an IBAction to the action button. The best way to do this is to select the text view and then </span>Control-drag the from text view to an opened ViewController.h file. Do likewise for the action button. You will end up with the following in the the ViewController.h file:<br /><font color="#33CC00">@property (weak, nonatomic) IBOutlet UITextView *aTextView;<br />- (IBAction)actionBtnClicked:(id)sender;</font><br /><span>And then in the ViewController.m file, add or update the automatically added @synthesize statement to:</span><br /><font color="#33CC00">@synthesize aTextView = _aTextView;</font>&nbsp; <br />(I think in the latest version of Xcode, you don't neet this @synthesize statement, as the compiler will create the property as if it is there, but I like to put it there for clarity.)<br /></div> <hr style="width:100%;clear:both;visibility:hidden;"></hr>  <div class="paragraph" style="text-align:left;"><strong>Step 3: Add the codes for IBAction</strong><br /><span></span>Add the following codes inside - (IBAction)actionBtnClicked:(id)sender <br /><font color="#33CC00">if(NSClassFromString(@"UIActivityViewController")!=nil){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [self showActivityViewController];<br />&nbsp;&nbsp;&nbsp; }else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [self showActionSheet];<br />&nbsp;&nbsp;&nbsp; }</font><br /><span></span>This essentially tests whether the UIActivityViewController class is available (it would be if you are using iOS 6+). If it is available, we would use that, otherwise we have to implement a fall back method. <br /><br /><strong><span>Step 4: Write the code for the showActivityViewController method</span></strong><br />Next, we write the codes for the activity view controller.<br /><span>Before we do that insert the following just before the @implement statement in ViewController.m:</span><br /><span></span><font color="#33CC00">@interface ViewController ()<br />-(void)showActivityViewController;<br />-(void)showActionSheet;<br />@end</font><br />This is not essential; but it is my habit and what I consider good practice.<br /><span></span>Now, the codes:<br /><font color="#33CC00">-(void)showActivityViewController<br />{<br />&nbsp;&nbsp;&nbsp; //-- set up the data objects<br />&nbsp;&nbsp;&nbsp; NSString *textObject = _aTextView.text;<br />&nbsp;&nbsp;&nbsp; NSURL *url = [NSURL URLWithString:@"http://www.absoluteripple.com"];<br />&nbsp;&nbsp;&nbsp; UIImage *image = [UIImage imageNamed:@"heart.jpg"];<br />&nbsp;&nbsp;&nbsp; NSArray *activityItems = [NSArray arrayWithObjects:textObject, url, image, nil];<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; //-- initialising the activity view controller<br />&nbsp;&nbsp;&nbsp; UIActivityViewController *avc = [[UIActivityViewController alloc]<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; initWithActivityItems:activityItems<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; applicationActivities:nil];<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; //-- define the activity view completion handler</font><br /><span></span><font color="#33CC00">&nbsp;&nbsp;&nbsp; avc.completionHandler = ^(NSString *activityType, BOOL completed){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Activity Type selected: %@", activityType);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (completed) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Selected activity was performed.");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (activityType == NULL) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"User dismissed the view controller without making a selection.");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Activity was not performed.");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; };<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; //-- define activity to be excluded (if any)<br />&nbsp;&nbsp;&nbsp; avc.excludedActivityTypes = [NSArray arrayWithObjects:UIActivityTypeAssignToContact, nil];<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; //-- show the activity view controller<br />&nbsp;&nbsp;&nbsp; [self presentViewController:avc<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; animated:YES completion:nil];<br />&nbsp;&nbsp;&nbsp; <br />}</font><br />The <font color="#3366FF">activityItems</font> is simply an array of data objects on which to perform the activity. In this example, it contains a text object, url object and an image object. The image object here is jpeg file named "heart.jpg" that have been added to xcode project.<span></span><br /><span>The </span><font color="#3366FF">applicationActivities</font> parameter is for you to provide custom services. Here it is set to nil as we are not providing any.<br /><span></span>You do not need to implement the <font color="#3366FF">activity view completion handler</font> if you do not need it. It simply allows your app to know whether the user has performed a particular activity or not and react to that accordingly if required.<br /><span>The </span><font color="#3366FF">excludedActivityTypes</font> is an array of ActivityType that you do not want to present to the user. By default, it will display all standard services that can handle the data objects that you included in the <font color="#3366FF">activityItems</font>. This standard list includes things like copying items to the pasteboard, posting content to social media sites, sending items via email or SMS. Here, I have excluded adding to contact as an example. Consult the iOS developer reference for other constant string you can use.<br />Test it in the Simulator. Make sure you are using iPhone 6.0. When the app appears, click the action button and the following activity view should present itself. If you then click one of the Social network icons, such as Facebook, the standard iOS 6 social network posting interface will appear and it will contain the text you put into the text view, the url and the photo you included in the code. <br /><br /></div>  <div><div class="wsite-image wsite-image-border-thin " style="padding-top:10px;padding-bottom:10px;margin-left:0;margin-right:0;text-align:center"> <a> <img src="https://www.absoluteripple.com/uploads/4/8/5/4/4854975/7425087.png?168" alt="Picture" style="width:auto;max-width:100%" /> </a> <div style="display:block;font-size:90%"></div> </div></div>  <div class="paragraph" style="text-align:left;"><strong style="">Step 5: Write the code for the showActionSheet method</strong><br />This method deals with the pre-iOS 6.0 situation. The fallback method can be anything you like. In this simple example, an Activity Sheet will be presented as an alternative.<br /><span>First, make the ViewController conform to the UIActionSheetDelegate by going to the ViewController.h file and update the @interface statement to read as follows:</span><br /><span></span><font color="#33CC00">@interface ABSViewController : UIViewController &lt;UIActionSheetDelegate&gt;</font><br /><span>Now the codes:</span><br /><span></span><font color="#33CC00">//-- for compability with pre iOS 6.0<br />-(void)showActionSheet<br />{<br />&nbsp;&nbsp;&nbsp; UIActionSheet *as = [[UIActionSheet alloc]initWithTitle:@"choose"<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; delegate:self<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cancelButtonTitle:@"Cancel"<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; destructiveButtonTitle:nil<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; otherButtonTitles:@"Email", nil];<br />&nbsp;&nbsp;&nbsp; [as showInView:self.view];<br />}</font><br /><br /><font color="#33CC00">#pragma mark - UIActionSheet delegate<br />-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex<br />{<br />&nbsp;&nbsp;&nbsp; switch (buttonIndex) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case 0:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Email");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case 1:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSLog(@"Cancel");<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; default:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br />&nbsp;&nbsp;&nbsp; }<br />}</font><br />This simply print out an NSLog. In real app, you will need to write the code to handle the various choices.<br /><span></span>Now, if you can test it in the Simulator. Select iPhone 5.0 or 5.1. When the  app appears, click the action button and an action sheet  should present itself instead of the activity view.<br /></div>  <div class="paragraph" style="text-align:left;">This is all you need to do. As alluded to above, this class allows you to add custom services that your app may wish to provide. You define this via the <font color="#3366FF">applicationActivities</font> parameter when you initalise the activity view controller. The next post will illustrate how to implement this.<br /></div>]]></content:encoded></item><item><title><![CDATA[Invoking the Map App to provide routing direction]]></title><link><![CDATA[https://www.absoluteripple.com/resources/invoking-the-map-app-to-provide-routing-direction]]></link><comments><![CDATA[https://www.absoluteripple.com/resources/invoking-the-map-app-to-provide-routing-direction#comments]]></comments><pubDate>Thu, 18 Oct 2012 04:33:49 GMT</pubDate><category><![CDATA[ios programming]]></category><guid isPermaLink="false">https://www.absoluteripple.com/resources/invoking-the-map-app-to-provide-routing-direction</guid><description><![CDATA[This post briefly describes how to invoke the Map app from your own app to provide routing direction from your current location to a particular destination coordinate.(Step 1 and 2 below can be skipped if you only want to use iOS 6.)  Step 1: Include the CoreLocation frameworkYou need to first include the CoreLocation Framework in your project. Then you need import that framework in the relevant project class file:#import &lt;CoreLocation/CoreLocation.h&gt;Step 2: Add codes to obtain the current [...] ]]></description><content:encoded><![CDATA[<div class="paragraph" style="text-align:left;">This post briefly describes how to invoke the Map app from your own app to provide routing direction from your current location to a particular destination coordinate.<br /><span>(Step 1 and 2 below can be skipped if you only want to use iOS 6.)</span><br /></div>  <div class="paragraph" style="text-align:left;"><strong>Step 1: Include the CoreLocation framework</strong><br /><span></span>You need to first include the CoreLocation Framework in your project. Then you need import that framework in the relevant project class file:<br /><font color="#3366FF">#import &lt;CoreLocation/CoreLocation.h&gt;</font><br /><strong>Step 2: Add codes to obtain the current location</strong><br /><span></span>First, you need an object to hold the current location. In the .h file:<br /><font color="#3366FF">@property (nonatomic, strong) CLLocation *currentLocation;</font><br /><span>And in the corresponding .m file:</span><br /><span></span><font color="#3366FF">@synthesize currentLocation = _currentLocation;</font><br /><span>Next you need to make the class adopt to the CLLocationManagerDelegate protocol. So add </span><font color="#3366FF">&lt;CLLocationManagerDelegate&gt; </font>to the @interface.<br /><br /><span>In viewDidLoad, insert:</span><br /><span></span><font color="#3366FF">if ([CLLocationManager locationServicesEnabled]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //- initialise location manager<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CLLocationManager *locManager= [[CLLocationManager alloc] init];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; locManager.delegate = self;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; locManager.desiredAccuracy = kCLLocationAccuracyBest;&nbsp; // modify to set desire accuracy<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; locManager.distanceFilter = kCLDistanceFilterNone;&nbsp;&nbsp; // modify if required &nbsp;&nbsp;&nbsp;&nbsp; <br /><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>[locManager setPurpose:@"This app will use your location to determine your current position."];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [locManager startUpdatingLocation];<br />&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //-- show an alert or whatever...;<br />&nbsp;&nbsp;&nbsp; }</font><br />This first check if location service is available, then if it is, an instance of the location manager is created and start the location update.<br /><span>Next, implement the following method in the CLLocationManagerDelegate protocol:</span><br /><span></span><font color="#3366FF">- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation<br />{<br />&nbsp;&nbsp;&nbsp; //- only use relatively recent event<br />&nbsp;&nbsp;&nbsp; NSDate* eventDate = newLocation.timestamp;<br />&nbsp;&nbsp;&nbsp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];<br />&nbsp;&nbsp;&nbsp; if (abs(howRecent) &lt; 15.0) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; newLocation.coordinate.latitude,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; newLocation.coordinate.longitude);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.currentLocation = newLocation;<br />&nbsp;&nbsp;&nbsp; }<br /><span>}</span></font><br />This method will be called once a location fix occurs. The coordinate is passed to the currentLocation object that you have created. The above code also provide a check to make sure that the location is not too old. If you don't need to do that, you can simply replace the above with:<br /><span></span> <font color="#3366FF">self.currentLocation = newLocation;</font><br /><span></span><br /></div>  <div class="paragraph" style="text-align:left;"><strong>Step 3: </strong><strong style="">Include the CoreLocation framework</strong><br />You  need to first include the MapKit Framework in your project. Then  you need import that framework in the relevant project class file:<br /><font color="#3366FF">#import &lt;MapKit/MapKit.h&gt;</font><br /></div>  <div class="paragraph" style="text-align:left;"><strong>Step 4: Codes to show invoke the Map App and Show the Route</strong><br /><span></span>Add the following method in your .m file:<br /><span></span><font color="#3366FF">- (void)showRouteInMapApp<br />{<br />&nbsp;&nbsp;&nbsp; Class itemClass = [MKMapItem class];<br />&nbsp;&nbsp;&nbsp; if (itemClass &amp;&amp; [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //- iOS 6<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CLLocationCoordinate2D destCoordinate = CLLocationCoordinate2DMake([_latitude doubleValue], [_longtitude doubleValue]);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: destCoordinate addressDictionary: nil];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; destination.name = @"NAME OF LOCATION...";<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MKLaunchOptionsDirectionsModeDriving,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MKLaunchOptionsDirectionsModeKey, nil];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [MKMapItem openMapsWithItems: items launchOptions: options];<br />&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //- use pre iOS 6<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //-- this opens in the map app<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NSString* url = [NSString stringWithFormat: @"maps://saddr=%f,%f&amp;daddr=%f,%f",<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _currentLocation.coordinate.latitude, _currentLocation.coordinate.longitude,[_latitude doubleValue],[_longtitude doubleValue]];<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];&nbsp; <br />&nbsp;&nbsp;&nbsp; }<br />}</font><br /><span></span>The above first check to see if you are using iOS 6. If so, it uses the new <font color="#33CC00">MKMapItem</font> approach, otherwise it uses an old approach to invoke the map app together with the current location coordinate determined via the codes in Step 1 and 2. <br /><span>Instead of opening the map app, you can open Google map in Safari by replacing the above url with the following:</span><br /><font color="#3366FF">NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&amp;daddr=%f,%f",<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _currentLocation.coordinate.latitude, _currentLocation.coordinate.longitude,[_latitude doubleValue],[_longtitude doubleValue]];</font><br /></div>]]></content:encoded></item></channel></rss>