Monday, May 30, 2011

How To Stop iTunes Automatically Syncing Your iPhone, iPod or iPad

iTunes Auto Sync Slowing You Down?

If you’re wondering how you can stop iTunes from automatically kicking off the sync + backup + update process when you plug your iOS device in then look no further.

By holding down the Shift + Control keys (Windows) or Command + Option keys (Mac) and then plugging your iPad, iPhone or iPod into your USB port you will tell iTunes not to sync!

If you happen to miss it and sync kicks off anyway, either slide the unlock slider on your device or hit the eject symbol in iTunes and your device will gracefully stop syncing and disconnect.

This was tested using both an iPad 2 and an iPhone 3GS on iTunes 10.2 (Mac).

Wednesday, May 25, 2011

iOS - File Sharing



File Sharing requires

  • The latest version of iTunes
  • Mac OS X v10.5.8 or later or an up-to-date version of Windows XP, Windows Vista, or Windows 7
  • An iOS device (with the latest version of iOS)
  • An iOS application that supports File Sharing

How to copy files using File Sharing

  1. Connect your iOS device to your computer using the included Dock Connector to USB cable.
  2. Launch iTunes 9.1 or later on your computer.
  3. Select your iOS device from the Devices section of iTunes.

    iTunes Devices section
  4. Click the Apps tab and scroll down to the bottom of the page.

    Note: If you do not see the File Sharing section shown in the image below, your iOS device does not have any apps that support File Sharing.

    iTunes File Sharing tab
  5. Under the File Sharing section, you'll find a list of apps currently installed on your iOS device that support File Sharing. Select an app to view a list of the files associated with that app on your iOS device.


    iTunes apps and documents list

How to copy files from your computer to your iOS app

  1. Be sure to select the appropriate application in the Apps list under File Sharing.
  2. Drag and drop files onto the Documents list to copy them to the app on your iOS device or…
  3. Click the Add… button, locate the file or files you want to copy from your computer, and click Choose. The selected files will be copied to the app on your iOS device immediately. Select only files that are supported by the iOS device app. Refer to the iOS app’s documentation to determine which file formats it supports.

    Copy to iPad dialog

How to copy files from an iOS app to your computer

  1. Be sure to select the appropriate application in the Apps list under File Sharing.
  2. Drag and drop files from the Documents list to a folder or window on your computer to copy them to your computer, or…
  3. Select the file or files you want to copy to your computer from the Documents list and click the "Save to…" button. Select only files that are supported by the iOS app. Refer to the iOS app’s documentation to determine which file formats it supports. Locate the folder on your computer to which you want to copy the files and click the Choose button. The selected files will be copied to the selected folder on your computer immediately.

    Copy to computer from iPad

 


Additional Information

How does File Sharing work?

File Sharing enables you to copy files from your computer to apps on your iOS device and from those apps to your computer. Not all iOS apps support File Sharing. Using File Sharing, files are copied into an iOS app and can only be opened from within that app if the app supports it. Refer to the documentation that came with the iOS app to determine supported file formats, and how to interact with shared documents.


Will I lose the files shared to an application if I delete that app from my iOS device?

Yes. Deleting an app on your iOS device with shared files will also delete the files on the iOS device associated with it. To avoid losing shared files on your iOS device associated with the app, back up and copy shared files to your computer frequently, and especially prior to deleting the application from your iOS device.

How do I back up shared files?

iTunes will back up the shared files on your iOS device when it syncs your iOS device with your computer. You cannot select and restore specific files from a backup, so be sure to copy files you have created on your iOS device frequently to a folder on your computer.

Where do I find files copied to apps on my iOS device?

The files you copy from your computer are only accessible from within the app on the iOS device to which you have copied the file. They are not accessible from other apps or locations on your iOS device. You can view the list of files under the File Sharing section of the Apps tab in iTunes when your iOS device is connected to your computer. See "How to copy files using File Sharing," above.


How do I delete files I copied to an app on my iOS device?

To delete a file you copied to an iOS device app using File Sharing:

  1. Attach your iOS device to your computer.
  2. Select your iOS device in the Devices section of iTunes.
  3. Click the Apps tab, then scroll down to the File Sharing section.
  4. Select the application from which you would like to delete a specific file.
  5. Select the file from the Documents list and press the Delete key on your keyboard.
  6. When prompted to confirm your request, click Delete.

    Delete confirmation window
  7. The file will be deleted from the app on your iOS device immediately.

Some applications may also support additional methods for deleting files. Refer to your application's documentation for further information.


How to Find Your iPhone’s Unique Identifier (UDID)


What is the UDID?


Each iPhone or iPod Touch has a Unique Device Identifier (UDID),
which is a sequence of 40 letters and numbers that is specific to your
device. It’s like a serial number but much harder to guess. It
will look something like this:
2b6f0cc904d137be2e1730235f5664094b831186.


Why do we need the UDID?


Your iPhone can only install programs that are approved by Apple.
Applications in the App Store have been approved by Apple for general
distribution, but beta customers get to try the app before it’s in the
store. We register your UDID with Apple so they can approve our
application especially for your iPhone.


How do I get my UDID?


You can copy/paste your UDID from iTunes or email it directly from
your device by using a free app from the App Store.


Email Using the Free App


Install and run
Ad Hoc Helper.
It will create an email with your UDID. Send it to nobody@example.com.


Copy/Paste from iTunes


  1. Launch iTunes and connect your iPhone.
  2. In the right pane, locate the information about your iPhone,
    including its name, capacity, software version, serial number, and
    phone number.

    Plugged-in-iphone
  3. Reveal the Identifier by clicking on Serial Number:.

    Clicked-serial-number
  4. Copy the Identifier to your clipboard by choosing EditCopy.
    Edit-copy
  5. Paste the Identifier into an email to nobody@example.com
    (You should be able to paste into your mail program or web browser by
    selecting EditPaste).

Tuesday, May 24, 2011

MTOM - OVER VIEW

MTOM OVERVIEW

With web services-based SOA now being deployed across Global 2000
enterprises, transmitting attachments such as MRI Scans, X-Rays, Design
Documents and Business Contracts using SOAP messages has become a
common practice. SOAP Message Transmission Optimization Mechanism (MTOM),
is a W3C Recommendation designed for optimizing the electronic
transmission of attachments. Through electronic transmission of
documents, corporations can realize significant cost savings and better
service levels by eliminating the use of postal mail. Paper-based
manual tasks can be replaced with simple and efficient electronic
processes where binary data can be transmitted between organizations
through standards such as MTOM.

MTOM provides an elegant mechanism of efficiently transmitting
binary data, such as images, PDF files, MS Word documents, between
systems. The Figure below shows the steps involved in transmitting data
between a Consumer and Producer using MTOM.



MTOM Process

The Consumer application begins by sending a SOAP Message that contains complex data in Base64Binary encoded format. Base64Binary data type represents arbitrary data (e.g., Images, PDF files, Word
Docs) in 65 textual characters that can be displayed as part of a SOAP
Message element. For the Send SOAP Message Step 1 in the Figure above, a sample SOAP Body with Base64Binary encoded element <tns:data> is as follows:


<soap:Body>

 <tns:ByteEcho>

 <tns:data>JVBERi0xLjYNJeLjz9MNCjE+DQpzdGFyNCjEx0YNCg==</tns:data>

</tns:ByteEcho>

</soap:Body>



An MTOM-aware web services engine detects the presence of Base64Binary encoded data types, <tns:data> in our example, and makes a decision – typically based on data size – to convert the Base64Binary data to MIME data with an XML-binary Optimization Package (xop) content type. The data conversion, shown in Step 2 of the Figure above, results in replacing the Base64Binary data with an <xop:Include> element that references the original raw bytes of the document being
transmitted. The raw bytes are appended to the SOAP Message and are
separated by a MIME boundary as shown below:

<soap:Envelope>

 <soap:Body>

  <tns:ByteEcho>

  <tns:data><xop:Include href="cid:1.633335845875937500@example.org"/></tns:data>

  </tns:ByteEcho>

 </soap:Body>

</soap:Envelope>

--MIMEBoundary000000

content-id: <1.633335845875937500@example.org>

content-type: application/octet-stream

content-transfer-encoding: binary



The raw binary data along with the SOAP Message and the MIME
Boundary is transmitted over the wire to the Producer. The Producer
then changes the raw binary data back to Base64Binary encoding for further processing. With this conversion between Base64Binary and raw binary MIME types, MTOM provides two significant advantages:

  1. Efficient Transmission: Base64Binary encoded data is ~33%
    larger than raw byte transmission using MIME. MTOM therefore reduces
    data bloat by converting Base64Binary encoding to raw bytes for
    transmission.
  2. Processing Simplicity: Base64Binary encoded data is composed
    of 65 textual characters. The data is represented within an element of
    a SOAP message. Security standards such as WS-Signatures and
    WS-Encryption can directly be applied to the SOAP Message. Once such
    operations are performed, the Base64Binary data can be
    converted to raw bytes for efficient transmission. Securing document
    transmission via SOAP, therefore, does not require additional standards
    for securing MIME-based attachments.

In this paper, we will deploy a web service for processing binary data ByteEcho(byte[] data) and examine using this service without MTOM and with MTOM enabled.

SETUP AND INSTALLATION OVERVIEW

For a hands-on understanding of MTOM, we will build web services
with simple operation that will echo a byte stream. In this section, we will
focus on setting up the SOA Testing framework for MTOM by installing
the following components. Install the three products below in the
listed sequence:

  1. Crosscheck Networks SOAPSonar Enterprise Edition:
    A .NET-based SOAP client used for comprehensive web services testing.
    Install pre-requisites that the SOAPSonar installer will ask you for
    such as .NET Framework 2.0 if it is not already installed on your
    machine.
  2. Web Service Enhancements (WSE) 3.0 for Microsoft .NET Framework:
    This is an add-on to Microsoft .NET Framework 2.0 that enables
    developers to build secure Web services based on the latest Web
    services protocol specifications such as MTOM. Note: During installion, please select the Developer Version option.
  3. Microsoft .NET WebMatrix: This installer includes an IDE for building web services and a lightweight web server.

All three components can be installed on a Windows 2000/XP/2003/Vista
machine with moderate resources. The web services Producer is the .NET
WebMatrix server that supplies a web service with the ByteEcho(byte[] data) operation that applications can invoke, over HTTP. In addition, it
produces the WSDL file that defines the web service interface. This
file provides all the necessary information for the consumer,
SOAPSonar, to send SOAP requests to the target web service. SOAPSonar
consumes and interprets the WSDL-based API published by the producer
and invokes the web service.

BUILDING A WEB SERVICE FOR BINARY DATA

To build a simple web service that illustrates handling binary data, follow these steps:

  1. Goto: Start > All Programs > Microsoft ASP .NET Web Matrix > ASP .NET Web Matrix.
  2. You will be prompted for with a screen shown below. Fill in the
    information as shown. Select "Web Services" in the left panel and the
    "Simple" template in the right panel. Create a C:\WebServices folder to store the .asmx file and picked C#.
  3. Create a New File in WebMatrix

    Note: The OK button will be grayed until all the information on this panel is filled out.

  4. This will auto-generate a web service for you with an Add(int a, int b) operation as shown below. We will keep this auto-generated operation
    and include a new byte processing operation in the next step.
  5. WebMatrix C# Code

  6. Cut and paste the following code in the Web Matrix IDE right under the Add(int a, int b) operation:
  7. [WebMethod] public byte [] ByteEcho(byte[] data) { return data; }

  8. The IDE will look as follows:
  9. WebMatrix Code for Processing Binary Data

  10. Hit the play button in the IDE and it will prompt you for the start
    the web application on port 8080. Your local firewall may prevent you
    from starting a listener on port 8080. Add the port to your firewall's
    list of allowable ports.
  11. Screen Shot to show WebMatrix Server Starup on Application Port

  12. A web browser with operation Add and ByteEcho will appear. You can
    click this and start playing with the Add operation. The ByteEcho operation does not accept input from the browser.

SOAPSonar SETUP

To setup the SOAPSonar test client, perform the following steps:
  1. Goto: Start > All Programs > Crosscheck Networks > SOAPSonar Enterprise Edition 3 > SOAPSonar Enterprise to launch SOAPSonar.
  2. Load the WSDL published at the .NET WebMatrix Endpoint http://localhost:8080/BinaryProcess.asmx?WSDL into SOAPSonar as shown in the figure below. Select the ByteEcho_1 test case in the left Project Tree Panel. Right click on the data field and select Content Function > Base64Encode.
    File Dialog will pop up to enable you to select a file from your system
    such as a PDF or JPEG file. The filename will be embedded in the data
    field with a $b64:file prefix. Click SOAPSonar Save to commit changes and SOAPSonar Run to execute the test. You will see the SOAP response in the Response Panel.
  3. SOAPSonar Load WSDL

  4. Save the project by going to File > Save Project As.
  5. Click SOAPSonar Header on in the Request Panel to review the Header information for
    the request. Select the (Sent Request) Tab as show in the Figure below.
    The SOAP request and the Header information are also shown below. Make
    a note of the following information:
    1. Header Content-Length is 324771 bytes. This will vary based on the file you select.
    2. Content-type is text/xml. This will change when MTOM is enabled.
    3. The data field contains base64Encoded value of the selected binary file.


So far, you have successfully loaded a WSDL into the test client,
SOAPSonar and setup a simple consumer (SOAPSonar) to producer
(webMatrix) Framework to send base64Encoded bytes to the webMatrix
server that reflects the bytes to SOAPSonar in the SOAP Response. Next,
we will enable MTOM and review its impact on the SOAP Request and
Response.

ENABLING MTOM

In the section, we will enable MTOM for WebMatrix and the SOAPSonar test client. To enable MTOM for webMatrix as follows:

  1. Goto C:\Program Files\Microsoft WSE\v3.0\Tools and launch WseConfigEditor3.exe.
  2. With the WSE 3.0 Configuration tool, select the File Menu to open the web.config file located in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG.
  3. Under the General Tab, check both boxes to enable WSE 3.0 for the WebMatrix sever as shown in the Figure below:
  4. WSE 3.0 Configurator

  5. Next, select the Messaging Tab and select “always” for the Server Mode MTOM Settings.
  6. WSE 3.0 Configurator

  7. Goto File > Save to the new configuration and Exit from the WSE 3.0 configuration tool.
  8. Review the web.config file using a text editor and ensure that the
    following elements appear in the web.config file. As expected, the
    serverMode value for MTOM is set to “always.” The server will now only
    accept MTOM encoded messages. If a SOAP request is received by
    WebMatrix that is not MTOM, an HTTP error 415: "Media unsupported" is
    returned to the sender.
  9. <messaging>  <mtom clientMode="Off" serverMode="always"/> </messaging>
  10. Re-send the base64Encoded SOAP request. Since WebMatrix receives a
    message that is not MTOM, an HTTP error 415: "Media unsupported" is
    returned to the SOAPSonar as displayed in the Response Panel.
  11. In the Project Tree, click on the Policy Settings node. Change the
    MTOM Setting – Client Mode to On as shown in the Figure below. This
    enables SOAPSonar to send MTOM encoded messages. Click to commit
    changes.
  12. SOAPSonar MTOM Setting

  13. Goto the ByteEcho_1 test case and click SOAPSonar MTOM Messages to execute the test.
    Review the request sent to the server by clicking on the (Send Request)
    Tab in the Request Panel. The SOAP request and the Header information
    are also shown below. Make a note of the following information:
    1. Header Content-Length is 244093 bytes. This will vary based on the file you select.
    2. Content-type is application/xop+xml. This indicates that an MTOM message is being generated by SOAPSonar.
    3. The data field contains MIMEBoundary content-transfer-encoding.

    SOAPSonar MTOM Messages

    Note: The Header Content Length for the Message Request with MTOM turned-on is 244K compared to 325K with the Message Request without MTOM. This corresponds to a ~25% reduction in message size even for a moderately sized message.

  14. Goto the panel shown in Step 8 above and check Show Raw Response
    for the MTOM settings. This turns-off the binary to text-encoding and
    enables you to view the raw binary content in the response panel.

You should be now be comfortable with sending base64Binary encoded and
MTOM encoded messages to a test server and viewing the responses in
wire format and base64Binary encoded formats.

CONCLUSIONS

MTOM provides an efficient mechanism for transmitting binary data.
MTOM’s approach of reducing the number of standards required for
transmission while reducing the data bloat caused by Base64Binary encoding the entire attachment makes it an ideal standard for
transmission of large binary content. Obviously, nothing comes for
free. The gain in network transmission efficiency by reducing “wire
footprint” is at the expense of CPU resources. The client has to expend
processing resources to convert Base64Binary encoded type to
MIME type before transmitting it over the wire. The receiver then
performs another data type transformation from MIME to Base64Binary data. MTOM is ideal for use cases where a large number of external
organizations want to transmit sizeable documents to an enterprise over
the internet with low bandwidth availability.

REFERENCES

  1. Faster Data Transport Means Faster Web Services with MTOM/XOP.
  2. XML, SOAP and Binary Data.
  3. Getting Started: Creating a WSE 3.0 Enabled Web Service to Transfer Large Amount of Data using WSE 3.0 MTOM.

Sunday, May 22, 2011

Understanding MTOM

MTOM combines the composability of Base 64 encoding with the transport efficiency of SOAP with Attachments. Non-XML data is processed just as it is with SOAP with Attachments SWA – the data is simply streamed as binary data in one of the MIME message parts. (The MTOM processing model is described in greater detail below.)

MTOM is composed of three distinct specifications:

* MTOM CORE describes an abstract feature for optimizing the transmission and/or wire format of a SOAP 1.2 message by selectively encoding portions of the message, while still presenting an XML Infoset to the SOAP application. Use of the Abstract SOAP Transmission Optimization Feature is a hop-by-hop contract between a SOAP node and the next SOAP node in the SOAP message path, providing no mandatory convention for optimization of SOAP transmission through intermediaries.
* XOP (XML-binary Optimization Packaging) specifies the method for serializing XML Infosets with non-XML content into MIME packages. XOP provides an alternate serialization that is fully compatible with a MIME package, including an XML document as the root portion of the package. XOP streams the non-XML attachment as one of the MIME message parts. The MIME attachment is processed and temporarily treated as base-64 encoded text immediately prior to serialization of the message. For example, a WS-Security layer creating a digital signature would use the non-XML data to calculate the signature by streaming it through a base-64-encoding layer. The base-64-encoded data is temporary, used only for creating the signature (it is never actually transferred, stored or serialized anywhere).

MTOM Processing Model - click for a larger view

During deserialization the processing layers that access the attachment would do so through the base-64-encoding layer (again, this is a temporary representation that occurs just before serialization).

* The Resource Representation SOAP Header Block specification defines a SOAP header block that can carry resource representations within SOAP messages. The Representation Header Block is designed to be used when the RECEIVER has limited ability to retrieve the resource (due to access restrictions or unreasonable overhead processing due to the size of the resource to be retrieved). The Representation Header Block can also be used when multiple references to the same resource are required but duplication of the resource is undesirable. The example below illustrates a sample application of the Representation Header Block. The referenced Content Package is attached as a MIME part and the (simulated) base-64 encoded value was generated during Infoset processing (as mentioned above).

What About SOAP with Attachments and DIME?

Why not simply use SOAP with Attachments (SwA) or DIME (Direct Internet Message Encapsulation)?

There are two disadvantages to using SwA:

* SwA defines a way for binding attachments to a SOAP envelope using the multipart/related MIME type - this is the same attachment/encapsulation mechanism used for e-mail. MIME is inefficient because it uses text strings to delineate boundaries between parts. Consumers must scan the entire message to find the string value used to delineate a boundary.
* MIME cannot be represented as an XML Infoset – this effectively breaks the web services model since attachments cannot be secured using WS-Security.

The DIME specification was created to address performance issues when processing MIME attachments. DIME avoided having to scan the entire message to locate boundaries because the length of the attached files was encoded in the message header, enabling large attachments to be processed in “chunks”. While DIME provided a more efficient processing model it still didn’t provide an infoset model for the message and attachment.

MTOM provides a compromise between the MIME model and the Web services model (an infoset representation is available – see the MTOM processing model above). MTOM messages are valid SWA messages, lowering the cost of supporting MTOM for existing SWA implementations. MTOM attachments are streamed as binary data within a MIME message part, making it fairly easy to pass MTOM attachments to SWA or receive SWA attachments into an MTOM implementation.

Sunday, May 15, 2011

How to Get the RGB Color Code from hex code

- (UIColor *) RGBColorCodeWithHCode: (NSString *) Hexcode{
NSString *colorstr = [[Hexcode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([colorstr length] < 6)
return [UIColor blackColor];
// strip 0X if it appears
if ([colorstr hasPrefix:@"0X"])
colorstr = [colorstr substringFromIndex:2];
if ([colorstr length] != 6)
return [UIColor blackColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rcolorString = [colorstr substringWithRange:range];
range.location = 2;
NSString *gcolorString = [colorstr substringWithRange:range];
range.location = 4;
NSString *bcolorString = [colorstr substringWithRange:range];
// Scan values
unsigned int red, green, blue;
[[NSScanner scannerWithString: rcolorString] scanHexInt:&red];
[[NSScanner scannerWithString: gcolorString] scanHexInt:&green];
[[NSScanner scannerWithString: bcolorString] scanHexInt:&blue];

return [UIColor colorWithRed:((float) red / 255.0f)
green:((float) green / 255.0f)
blue:((float) blue / 255.0f)
alpha:1.0f];
}

Wednesday, May 11, 2011

iPad Modal View Controllers

Modal view controllers are well documented in the View Controller Programming Guide for iPhone OS but here is a quick recap of how to present and dismiss a modal view. To keep things simple I will cover the steps for presenting the modal view when a button is pressed on a master view controller. When the button is pressed we need to create and show a detail view controller that contains a button that the user can use to dismiss the modal view controller. The NIB file for the detail view controller is trivial in this example consisting of just a single view containing a text label.

Allocating and showing the detail view controller is straightforward:

- (void)buttonAction:(id)sender {
// Create the modal view controller
DetailViewController *viewController = [[DetailViewController alloc]
initWithNibName:@”DetailViewController” bundle:nil];
// We are the delegate responsible for dismissing the modal view
viewController.delegate = self;
// Create a Navigation controller
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:viewController];
// show the navigation controller modally
[self presentModalViewController:navController animated:YES];
// Clean up resources
[navController release];
[viewController release];
}



After allocating and initializing the controller from its NIB file the delegate (which I will explain shortly) is set to the current master view controller. The important step is that we do not display the detail view controller directly. We actually create a navigation bar controller and initialize it with the detail view controller. This provides a convenient navigation bar to hold a button for dismissing the view. Once the navigation bar is configured correctly it is displayed with the presentModalViewController method of UIViewController.

The detail view controller needs to add a “Done” button to the naviagtion bar which will trigger the master view controller to dismiss the modal view. The viewDidLoad method is the best place to add the button:

- (void)viewDidLoad {
[super viewDidLoad];
// Override the right button to show a Done button
// which is used to dismiss the modal view
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(dismissView:)] autorelease];
}

The target action of the button is the method dismissView in the detail view controller. Best practise is that the view controller that created the modal view should also dismiss it. We could do this by adding an instance variable to the detail view controller of type MasterViewController and initialize it to contain a reference to the master view controller when we first create the modal view. However this makes the DetailViewController directly dependent on the master view controller which is a pain if we later want to use this modal view from elsewhere in the application.

A better solution is to make use of the delegate protocol pattern. We define a protocol in the detailViewController that all callers of the modal view must implement. The protocol ensures that all delegates of our class must implement the didDismissModalView method:

@protocol ModalViewControllerDelegate
- (void)didDismissModalView;
@end



The interface for the DetailViewController contains a weak reference to the delegate as follows:

@interface DetailViewController : UIViewController {
id delegate;
}

@property (nonatomic, assign) id delegate;



You should also remember to @synthesize delegate in the implementation of DetailViewController. We can now implement the dismissView method in the DetailViewController:

// Done button clicked
- (void)dismissView:(id)sender {
// Call the delegate to dismiss the modal view
[delegate didDismissModalView];
}



This illustrates the advantage of delegation. The DetailViewController does not now need to know who the calling controller is it only has to call the didDissmisModalView method. The compiler ensures that this method exists in the calling controller. The MasterViewController must declare that it implements the delegation protocol:

#import “DetailViewController.h”
@interface MasterViewController : UIViewController {
UIButton *button;
}

@property (nonatomic,retain) IBOutlet UIButton *button;

- (IBAction)buttonAction:(id)sender;

@end



In this simple example the implementation of the didDismissModalViewmethod is trivial:

- (void)didDismissModalView {
// Dismiss the modal view controller
[self dismissModalViewControllerAnimated:YES];
}



In more complex situations this method might validate changes to an object made by the user in the modal view prior to updating the model. The Apple View Controller Programming Guide nicely sums up the advantages of this approach:

* The delegate object has the opportunity to validate or incorporate changes from the modal view controller before that view controller is dismissed.

* The use of a delegate promotes better encapsulation because the modal view controller does not have to know anything about the parent object that presented it. This enables you to reuse that modal view controller in other parts of your application.

Modal Presentation Styles

Prior to iPhone OS 3.2 the modal view filled the whole screen which on an iPhone sized device is probably the only option. However with the larger screen size of an iPad there are some more options to control the appearance of the modal view. There is a new view controller property named modalPresentationStyle which allows you to select the required style when creating the view controller:

* UIModalPresentationFullScreen: This is the default style and as the name suggests causes the modal view to be presented full screen exactly as with the iPhone
* UIModalPresentationPageSheet: The modal view occupies the full screen height but the width is set to the width of the screen in portrait mode. This means that when the device is in portrait mode it still occupies the full screen. However in landscape mode it leaves some of the underlying master view to still be visible, but dimmed as the user cannot interact with the uncovered master view controller.
* UIModalPresentationFormSheet: Both the width and height of the modal view are set to be smaller than the screen size. The modal view is centered on the screen and the uncovered areas of the master view controller are dimmed to prevent user interaction. If the modal view makes used of the keyboard the modal view is moved upwards to make room.
* UIModalPresentationCurrentContext: The modal view is displayed using the same style as the parent master view controller.

The differences between the Page and Form sheet styles in landscape mode are easier to see than explain:

Using these new styles can make for a better user experience when what you have to display cannot usefully take advantage of the larger full screen space on the iPad. Showing the detailed content in a smaller than full screen window with the rest of the interface dimmed can help the user focus on the modal view. Note that on an iPhone or iPod Touch the modal view controller is always displayed full screen. To use one of the new presentation styles set the property on the controller you are presenting modally. In our previous example this would be the navigation controller in the buttonAction method of the master view controller:

navController.modalPresentationStyle = UIModalPresentationFormSheet;

There are some limitations on when you can use these new styles. If you are using the UIModalTransitionStylePartialCurl style for example you must use the full screen presentation style or you will get an exception.
Modal Views in Popovers

One final change introduced in iPhone OS 3.2 that impacts modal view controllers is their use with popovers. A popover is generally expected to be dismissed when the user touches outside of the popover. Of course if you are displaying a modal view controller in the popover this behaviour is probably not what you want. To prevent this you can set the modalInPopover boolean for the view controller. With the flag set the popover will not be dismissed by touches outside of the popover.

Monday, May 9, 2011

iPhone-iPad Development Tips

1. Screen Resolution;

iPhones are available in different screen resolutions; It is in 320×480 and the iPhone 4 screen resolution is 640×960. Same in caes of iPad; Currently it is 1024×768 and iPad 2 likely to have 2048×1536 screen resolution; So we need to care about this while playing with layouts; Here is a code to determine screen size;

CGRect currentScreen = [[UIScreen mainScreen] bounds];
currentScreen.size.width will return the width of screen;
currentScreen.size.height will return height of screen;

Note: If you rotate your screen to landscape, then height will become width and vise versa;

2. Device Type;

Following piece of code will tell you whether your application is running on iPhone or iPad;

UIDevice* currentDevice = [UIDevice currentDevice];
if(currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
NSLog(@"oh its iPad");
}else{
NSLog(@"This is iPhone");
}

3. Current iOS version;

UIDevice* currentDevice = [UIDevice currentDevice];
float systemVersion = [currentDevice.systemVersion floatValue];

This float value will tell you the current iOS version of device;

4. Current Orientation;

It is common to have different layout for single application in portrait and/or landscap view; In case of iPad it become more significant; Following method will tell you the current orientation of user’s device;


-(int) currentLayout{
if (([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait ||

[[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortraitUpsideDown))

// do something for portrait view;

else

// do something for landscape view;
}

Friday, May 6, 2011

iOS - Architecture


Cocoa Touch Layer - features

Multitasking

Applications built using iOS SDK 4.0 or later (and running in iOS 4.0 and later) are not terminated when the user presses the Home button; instead, they shift to a background execution context. The multitasking support defined by UIKit helps your application transition to and from the background state smoothly.
To preserve battery life, most applications are suspended by the system shortly after entering the background. A suspended application remains in memory but does not execute any code. This behavior allows an application to resume quickly when it is relaunched without consuming battery power in the meantime. However, applications may be allowed to continue running in the background for the following reasons:
  • An application can request a finite amount of time to complete some important task.

  • An application can declare itself as supporting specific services that require regular background execution time.

  • An application can use local notifications to generate user alerts at designated times, whether or not the application is running.

Regardless of whether your application is suspended or continues running in the background, supporting multitasking does require additional work on your part. The system notifies your application as it transitions to and from the background. These notification points are your cue to perform any important application tasks such as saving user data.

Printing

Introduced in iOS 4.2, the UIKit printing support allows applications to send content wirelessly to nearby printers. For the most part, UIKit does all of the heavy lifting associated with printing. It manages the printing interfaces, works with your application to render the printable content, and handles the scheduling and execution of print jobs on the printer.
Print jobs submitted by your application are handed off to the printing system, which manages the actual printing process. Print jobs from all applications on a device are queued and printed on a first-come, first-served basis. Users can get the status of print jobs from the Print Center application and can even use that application to cancel print jobs. All other aspects of printing are handled for you automatically by the system.

Data Protection

Introduced in iOS 4.0, data protection allows applications that work with sensitive user data to take advantage of the built-in encryption available on some devices. When your application designates a specific file as protected, the system stores that file on-disk in an encrypted format. While the device is locked, the contents of the file are inaccessible to both your application and to any potential intruders. However, when the device is unlocked by the user, a decryption key is created to allow your application to access the file.
Implementing data protection requires you to be considerate in how you create and manage the data you want to protect. Applications must be designed to secure the data at creation time and to be prepared for access changes when the user locks and unlocks the device.

Apple Push Notification Service

Introduced in iOS 3.0, the Apple Push Notification Service provides a way to alert users of new information, even when your application is not actively running. Using this service, you can push text notifications, add a badge to your application icon, or trigger audible alerts on user devices at any time. These messages let users know that they should open your application to receive the related information.
From a design standpoint, there are two parts to making push notifications work for iOS applications. First, the application must request the delivery of notifications and process the notification data once it is delivered. Second, you need to provide a server-side process to generate the notifications in the first place. This process lives on your own local server and works with Apple Push Notification Service to trigger the notifications.

Local Notifications

Introduced in iOS 4.0, local notifications complement the existing push notification mechanism by giving applications an avenue for generating the notifications locally instead of relying on an external server. Applications running in the background can use local notifications as a way to get a user’s attention when important events happen. For example, a navigation application running in the background can use local notifications to alert the user when it is time to make a turn. Applications can also schedule the delivery of local notifications for a future date and time and have those notifications delivered even if the application is not running.
The advantage of local notifications is that they are independent of your application. Once a notification is scheduled, the system manages the delivery of it. Your application does not even have to be running when the notification is delivered.

Gesture Recognizers

Introduced in iOS 3.2, gesture recognizers are objects that you attach to views and use to detect common types of gestures such as swipes and pinches. After attaching a gesture recognizer to your view, you tell it what action to perform when the gesture occurs. The gesture recognizer object then tracks the raw touch events and applies the system-defined heuristics for what the given gesture should be. Without gesture recognizers, you must do all this work yourself, which can be quite complicated.
UIKit includes a UIGestureRecognizer class that defines the basic behavior for all gesture recognizers. You can define your own custom gesture recognizer subclasses or use one of the UIKit-supplied subclasses to handle any of the following standard gestures:
  • Tapping (any number of taps)

  • Pinching in and out (for zooming)

  • Panning or dragging

  • Swiping (in any direction)

  • Rotating (fingers moving in opposite directions)

  • Long presses

File-Sharing Support

Introduced in iOS 3.2, file-sharing support lets applications make user data files available via iTunes 9.1 and later. An application that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your application to share files with other applications on the same device; that behavior requires the pasteboard or a document interaction controller object.
To enable file sharing for your application, do the following:
  1. Add the UIFileSharingEnabled key to your application’s Info.plist file and set the value of the key to YES.

  2. Put whatever files you want to share in your application’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Applications that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately.

Peer-to-Peer Services

Introduced in iOS 3.0, the Game Kit framework provides peer-to-peer connectivity over Bluetooth. You can use peer-to-peer connectivity to initiate communication sessions with nearby devices and implement many of the features found in multiplayer games. Although primarily used in games, you can also use this feature in other types of applications.

Standard System View Controllers

Many of the frameworks in the Cocoa Touch layer contain view controllers for presenting standard system interfaces. You are encouraged to use these view controllers in your applications to present a consistent user experience. Whenever you need to perform one of the following tasks, you should use a view controller from the corresponding framework:
  • Display or edit contact information—Use the view controllers in the Address Book UI framework.

  • Create or edit calendar events—Use the view controllers in the Event Kit UI framework.

  • Compose an email or SMS message—Use the view controllers in the Message UI framework.

  • Open or preview the contents of a file—Use the UIDocumentInteractionController class in the UIKit framework.

  • Take a picture or choose a photo from the user’s photo library—Use the UIImagePickerController class in the UIKit framework.

  • Shoot a video clip—Use the UIImagePickerController class in the UIKit framework.


External Display Support

Introduced in iOS 3.2, external display support allows some iOS-based devices to be connected to an external display through a set of supported cables. When connected, the associated screen can be used by the application to display content. Information about the screen, including its supported resolutions, is accessible through the interfaces of the UIKit framework. You also use that framework to associate your application’s windows with one screen or another

Thursday, May 5, 2011

Reading and Writing plists

Reading a plist file from the application bundle just requires a few lines of code, and some error handling. I like to place that code in a nice convenience method like this:
 

- (id)readPlist:(NSString *)fileName {
   NSData *plistData;
   NSString *error;
   NSPropertyListFormat format;
   id plist;

   NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
   plistData = [NSData dataWithContentsOfFile:localizedPath];
   plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
   if (!plist) {
      NSLog(@"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
      [error release];
   }

   return plist;
}

I’m not too fond of using id as return values or parameters to methods. I prefer stronger type checks, so I typically wrap the readPlist method in two methods that return either an array or a dictionary.



- (NSArray *)getArray:(NSString *)fileName {
   return (NSArray *)[self readPlist:fileName];
}

- (NSDictionary *)getDictionary:(NSString *)fileName {
   return (NSDictionary *)[self readPlist:fileName];
}

Writing to a plist file is not much more difficult:

- (void)writePlist:(id)plist fileName:(NSString *)fileName {
   NSData *xmlData;
   NSString *error;

   NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
   xmlData = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
   if (xmlData) {
      [xmlData writeToFile:localizedPath atomically:YES];
   } else {
      NSLog(@"Error writing plist to file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
      [error release];
   }
}


Creating a New Navigation-Based Application

Open Up Xcode



You will be doing all of your development in Xcode. Then close the Welcome window (if it shows up)
Start a new iPhone OS Project
Click Xcode > New Project and a window should pop up like this:



Make sure Application is selected under iPhone OS and then select Navigation-Based Application. Click Choose… It will ask you to name your project.  Type in “Hello World” and let’s get started.

iPhone Programming Tutorial – UITableView Hello World

In this tutorial I will walk to you through creating a simple “Hello World” application using a UITableView for the iPhone.  There are many ways that a Hello World program could be made on the iPhone, I am going to show you the simplest.  This tutorial assumes you have a basic understanding of Objective-C.  Apple has provided a very simple and straight forward tutorial on Objective-C.  You can find it here.
You will learn how to:
This tutorial assumes that you have already installed the iPhone SDK.  If you are unsure how to do this, click and follow the steps.

Debugging Tutorial – Automating Your Tests With A UIRecorder Instrument

If you have ever experienced a bug in your application that took many steps to reproduce, then this tutorial is for you.  By nature, testing and debugging are very tedious processes.  This is especially the case for the iPhone.
Say you have an app that drills down 5-levels deep to some other view.  Now let’s say that you have a bug on that view 5 levels deep.  Your normal method of debugging is:
  • Run the app
  • Tap view 1
  • Tap view 2
  • Tap view 3
  • Tap view 4
  • Tap view 5
  • (Crash)
  • Change some code
  • Repeat
As you can see (and I’m sure have noticed), this sucks.  Well, Kendall Gelner gave a killer talk at 360iDev (which I recently attended) on various debugging tips using Instruments and XCode.  One of the most useful techniques (to me) was how to automate your testing.  Let me show you what I mean.

1. Open up the app you wish to test/debug
2. Launch it in the simulator
3. Open Instruments – This is located in /Developer/Applications/Instruments (just do a spotlight search for it)

screenshot_01

4. Select UIRecorder and click Choose - You should now see a window like this

screenshot_02

5. Now, we need to attach this tool to the iPhone Simulator process.  Click the drop-down above  

Default Target -> Attach to Process -> iPhone Simulator.


ss_03

6. Now click Drive & Record and do all of the steps in the simulator to test your app.  At this point, the UI Recorder is recording your every move.  When you have finished press the Stop button. Note: After you have recorded your actions, don’t move the simulator as it will mess up the entire process.
7. Modify your code…
8. Press the Drive & Record button and watch the magic happen.  The test is automatically done for you.  You should see your mouse move over to the simulator and the system mimicking every action that you did before.
That’s it! I know this isn’t a super long tutorial (or even a coding tutorial), but the UI Recorder has sped my test time up tremendously.  Give it a shot and let me know what you think.  Here is a short video of me going through all of the steps.

video tutorial

simple Navigationbased tutorial

It’s time to start displaying some drinks. You’ll need to make some modifications to both the RootViewController.h and RootViewController.m files

1Declare the drinks array.(in RootViewController.h )

@interface RootViewController : UITableViewController{
NSMutableArray* drinks;
}
@property (nonatomic, retain) NSMutableArray* drinks;
@end
(RootViewController.m)

@synthesize drinks;
-(void)dealloc{

[drinks release];

[super dealloc];

}

2 Implement and populate the array.(in RootViewController.m)
In RootViewController.m, uncomment and expand the ViewDidLoad methods.
Tell the table how many rows you have.
Populate the table cells.

- (void)viewDidLoad { [super viewDidLoad];
RootViewController.m
NSMutableArray* tmpArray = [[NSMutableArray alloc]

initWithObjects:@”Firecracker”, @”Lemon Drop”, @”Mojito”,nil];
self.drinks = tmpArray; [tmpArray release];
// Uncomment the following line to display an Edit button in

//the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self. editButtonItem;
}



3 Tell the table how many rows you have.

//Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.drinks count];
 
4 Populate the table cells

// Configure the cell.
cell.textLabel.text = [self.drinks objectAtIndex:indexPath.row];

return cell;
}
 
Now you’re ready to go. Save it, build and run, and you’ll see the three drinks in your app in the main view.

Backup iPhone Pictures – Mac Tips

Listen to this episode
When you have problems with your iPhone, you may have no other choice than to RESTORE it back to the factory state. Before you restore, iTunes says it is making a backup of your phone. However, it isn’t making a backup of any photos you have taken with it. So when the phone is restored, all of your photos will be gone. The good news is that If you have your iPhone set to sync your photos with iPhoto automatically when you plug it in, you may be OK. However, if you are like me and choose for the iPhone not to launch iPhoto when you connect it… well, you need to backup those pics.

How to do it:

1. Plug-in your iPhone and launch iPhoto. iPhoto will detect your iPhone, and you can now choose to import all or import selected pictures.
mactips_358_1.png
Doing this will add pictures you have taken with your iPhone into your iPhoto library.

Another Way – Image Capture

You can also use Image Captureimagecapture.png to do the same thing, but not add them to your iPhoto library.
1. Plug-in your iPhone. Launch Image Capture. You can find it in your Applications folder. If you don’t see it there, look in the Utilities folder. Note: On the podcast, I said it will be in the utilities folder… I forgot that it may reside in Applications.
2. Now it will detect your iPhone, and you can choose to Download Some or Download ALL to your Mac.
mactips_358_2.png

ScrollView example for TextField in iPhone

In the application when user input in the textfield then see UITextField is hidden under the keyboard.This problem solved using the ScrollView. So let see how it will be worked.
In this application we will see how to ScrollView worked in our application. This is the very simple application. In the application when user input in the textfield then see UITextField is hidden under the keyboard.This problem solved using the ScrollView. So let see how it will be worked.

Step 1: Create a View base application using the template. Give the application name “ScrollViewExample”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Expand classes and notice Interface Builder created the ScrollViewExampleViewController class for you. Expand Resources and notice the template generated a separate nib, ScrollViewExampleViewController.xib, for the “ScrollViewExample”.

Step 4: Open the ScrollViewExampleViewController.h file, we have added scrollview for scrolling the view,and two textfield for display the textbox. So make the following changes in the file:

#import
@interface ScrollViewExampleViewController : UIViewController {

IBOutlet UIScrollView *scrollview;
IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;

BOOL displayKeyboard;
CGPoint  offset;
UITextField *Field;
}

@property(nonatomic,retain) IBOutlet UIScrollView *scrollview;
@property(nonatomic,retain) IBOutlet UITextField *textField1;
@property(nonatomic,retain) IBOutlet UITextField *textField2;
 

Step 5: Double click your ScrollViewExampleViewController.xib file open it to the Interface Builder. First drag Scroll View from the library and place it to the view window and drag two TextField also, place it to the view window(See the figure below).Connect the File’s Owner icon to the View icon and select view. Select File’s Owner icon to the view and select scrollview. Next drag from the File’s Owner icon to the first textfield and select textfield1, do it once more time for the textfield2. Now save it, close it and go back to the Xcode.



Step 6: In the ScrollViewExampleViewController.m file make the following changes:

- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector
(keyboardDidShow:)
name: UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector
(keyboardDidHide:) name:
UIKeyboardDidHideNotification
object:nil];

scrollview.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH,
SCROLLVIEW_CONTENT_HEIGHT);
displayKeyboard = NO;
}

-(void) viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter]
removeObserver:self];
}

-(void) keyboardDidShow: (NSNotification *)notif {
if (displayKeyboard) {
return;
}

NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

offset = scrollview.contentOffset;

CGRect viewFrame = scrollview.frame;
viewFrame.size.height -= keyboardSize.height;
scrollview.frame = viewFrame;

CGRect textFieldRect = [Field frame];
textFieldRect.origin.y += 10;
[scrollview scrollRectToVisible: textFieldRect animated:YES];
displayKeyboard = YES;
}

-(void) keyboardDidHide: (NSNotification *)notif {
if (!displayKeyboard) {
return;
}

scrollview.frame = 
CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH, SCROLLVIEW_CONTENT_HEIGHT);

scrollview.contentOffset =offset;

displayKeyboard = NO;

}

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
Field = textField;
return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Step 7: Now compile and run the application in the Simulator.




Download Updated SourceCode ScrollViewExample 2

Features of iPhone4


5 Megapixel Camera with LED Flash

Take beautiful, detailed photos with the new 5-megapixel camera with built-in LED flash. The advanced backside illumination sensor captures great pictures even in low light. And the new front-facing camera makes it easy to take self-portraits.

overview-camera-20100607.jpg


Facetime

People have been dreaming about video calling for decades. iPhone 4 makes it a reality. With just a tap, you can wave hello to your kids, share a smile from across the globe or watch your best friend laugh at your stories — iPhone 4 to iPhone 4 over Wi-Fi. No other phone makes staying in touch this much fun.

Two cameras,
two views.

iPhone 4 has two cameras: one on the front, which focuses on you. And one on the back, which focuses on everything else. FaceTime lets you switch back and forth between them at any time during a video call. All you have to do is tap a button.

Retina display

The Retina display on iPhone 4 is the sharpest, most vibrant, highest-resolution phone screen ever, with four times the pixel count of previous iPhone models. In fact, the pixel density is so high that the human eye is unable to distinguish individual pixels. Which makes text amazingly crisp and images stunningly sharp.
overview-retina-20100608.jpg

Multitasking

iPhone 4 introduces a whole new way of multitasking. Now you can run your favourite third-party apps — and switch between them instantly — without slowing down the performance of the foreground app or draining the battery unnecessarily.1 This smarter approach to multitasking is available only on iPhone.
overview-multitasking-20100607.jpg

HD Video Recording and Editing

Shoot your own movies in high definition. Capture impressive video even in low-light settings, thanks to the advanced backside illumination sensor and built-in LED light. Then edit and create your own mini-masterpiece right on iPhone 4 using the new iMovie app — with Apple-designed themes, titles and transitions. It’s coming soon to the App Store.
overview-hd-20100607.jpg

Folders for Apps

Organise apps into folders for fast access to your favourites.

iBooks

Available as a free download, iBooks is an amazing ebook reader and a great place to buy books.

Home Screen

Get one-tap access to everything on your iPhone and change the wallpaper to match your mood.

iMovie

Edit video, add themes and music, and share your movies. It’s coming soon to the App Store.

Phone

Built-in noise suppression makes phone calls easier to hear.

Mail

A unified inbox and other new features make Mail more powerful than ever.

Safari

The most advanced web browser on a mobile phone.

iPod

Play music and watch video in luminous colour.

Photos

View photos by Albums, Events, Faces and Places.

Voice Control

Make a call or play a song using just your voice.

Messages

Send messages with text, video, photos and more.

Maps + Compass

Find locations, get directions and orient yourself on the map.

Keyboard

The smart keyboard helps you type quickly and accurately.

Search

Find what you’re looking for across your iPhone or the web.

App Store

Discover hundreds of thousands of apps that let you do even more.

Accessibility

iPhone 4 comes with screen-reading technology and other accessibility features. for more details

http://www.apple.com/iphone/