iDev: Copy a plist file to documents folder

Hi Friends,

Here a code snapshot for your help on Copy a plist file to Documents Folder

BOOL isSuccess;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"idevCopyData.plist"];
isSuccess = [fileManager fileExistsAtPath:filePath];
if (isSuccess) return;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"idevCopyData.plist"];
isSuccess = [fileManager copyItemAtPath:path toPath:filePath error:&error];
if (!isSuccess) {
NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]);
}

 

Reference : Here

Thanks 🙂

 

Advertisements

iDev: Change iOS project “My Mac 64-bit” to “iOS Device”

Hi Friends,

XCode iOS project only shows “My Mac 64-bit”!!!

The Simulator and Device options to Build/Run your have have disappeared.
This happened to  me after I changed the project name once or changed by another person.

solution #1:

  1. – Close Xcode.
  2. – Locate your Project folder.
  3. – Right-click on the AppName.xcodeproj file and click show package contents.
  4. – Now delete everything inside the xcuserdata folder.

If this does not work trying this:

  1. – open Xcode (obviously)
  2. – clicked on Manage Schemes and then Autocreate Schemes Now.
  3. – Then select the new scheme in Xcode.

Now you should get back all device/simulator options.

Thanks 🙂

Keep Coding 🙂

iDev: Secure site trust (Https:) in iOS using NSURLConnection

Secure Coding iPhone and iPad Apps Against MiTM

Many iOS applications use HTTP to connect to server side resources. To protect user-data from being eavesdropped, iOS applications often use SSL to encrypt their HTTP connections.

In this article, I will present sample Objective-C code to illustrate how HTTP(S) connections are established and how to locate insecure code that can leave the iOS application vulnerable to Man in the Middle attacks. I will also discuss how to configure an iOS device to allow for interception of traffic through an HTTP proxy for testing purposes.

A Simple App Using NSURLConnection

The easiest way to initiate HTTP requests in iOS is to utilize the NSURLConnection class. Here is sample code from a very simple application that takes in a URL from an edit-box, makes a GET request, and displays the HTML obtained.

[Please note that the code in this particular example is mostly from Apple’s wonderful tutorial on how to use NSURLConnection]

//This IBAction fires when the user types in a URL and presses GO
– (IBAction) urlBarReturn:(id)sender
{   
    //htmlOutput is the UITextView that displays the HTML
    htmlOutput.text=@””;

    //urlBar is the UITextField that contains the URL to load
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlBar.text]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(!theConnection)
        htmlOutput.text=@”failed”;   
}

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    //receivedData is of type NSMutableData
    [receivedData setLength:0];

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];

    NSString *tempString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    htmlOutput.text = [NSString stringWithFormat:@”%@%@”,htmlOutput.text,tempString];

    [tempString release];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    [connection release];

    [receivedData release];

    NSLog(@”Connection failed! Error: %@ %@”,
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

    htmlOutput.text=[NSString stringWithFormat:@”Connection failed! Error %@ %@”,[error localizedDescription],
                     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

    [connection release];

    [receivedData release];

}

The result is a simple iOS application that fetches HTML code from a given URL.

IOS-app-simple-html
Figure: Simple iOS App using NSURLConnection to fetch HTML from a given URL.

In the screen-shot above, notice that the target URL is https. NSURLConnection seamlessly establishes an SSL connection and fetches the data. If you are reviewing source code of an iOS application for your organization to locate security issues, it makes sense to analyze code that uses NSURLConnection. Make sure you understand how the connections are being inititated, how user input is utilized to construct the connection requests, and if SSL is being used or not. While you are at it, you may also want to watch for NSURL* in general to include invocations to objects of type NSHTTPCookie, NSHTTPCookieStorage, NSHTTPURLResponse, NSURLCredential, NSURLDownload, etc.

Man in the Middle 

74.125.224.49 is one of the IP addresses bound to the host name http://www.google.com. If you browse to https://74.125.224.49, your browser should show you a warning due to the fact that the Common Name field in the SSL certificate presented by the server (www.google.com) does not match the host+domain component of the URL.

IOS-safari-warning Figure: Safari on iOS warning the user due to mis-match of the Common Name field in the certificate.

As presented in the screen-shot above, Safari on iOS does the right thing by warning the user in this situation. Common Name mis-matches and certificates that are not signed by a recognized certificate authority can be signs of a Man in the Middle attempt by a malicious party that is on the same network segment as that of the user or within the network route to the destination.

Ios-NSURL-warning Figure: NSURLConnection’s connection:didFailWithError: delegate is invoked to throw a similar warning.

The screenshot above shows what happens if we attempt to browse to https://74.125.224.49 using our sample App discussed ealier: the connection:didFailWithError: delegate is called indicating an error, which in this case warns the user of the risk and terminates.

This is fantastic. Kudos to Apple for thinking through the security implications and presenting a useful warning message to the user (via NSError).

Unfortunately, it is quite common for application developers to over-ride this protection for various reasons: for example, if the test environment does not have a valid certificate and the code makes it to production. The code below is enough to over-ride this protection outright:

 

– (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

{
                [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

The details on this code is available from this stackoverflow post. There is also a private method for NSURLRequest called setAllowsAnyHTTPSCertificate:forHost: that can be used to over-ride the SSL warnings but Apps that use it are unlikely to get through the App store approval process (Apple prohibits invocations of private API).

If you are responsible for reviewing your organization’s iOS code for security vulnerabilities, I highly recommend you watch for such dangerous design decisions that can put your client’s data and your company’s data at risk.

Intercepting HTTPS traffic using an HTTP Proxy.

As part of performing security testing of applications, it is often useful to intercept HTTP traffic being invoked by the application. Applications that use NSURLConnection‘s implementation as-is will reject your local proxy’s self-signed certificate and terminate the connection. You can get around this easily by implanting the HTTP proxy’s self-signed certificate as a trusted certificate on your iOS device [Note: This is not a loop-hole against the precautions mentioned above: in this case we have access to the physical device and are legitimately implatining the self-signed certificate].

If you are using the Burp Proxy or the Charles Proxy, all you need to do is place the self-signed cert on a HTTP location and browse to it. Instructions for the Burp Proxy are available here, and instructions for Charles Proxy are also available.

Once you have your iOS device or simulator setup using the self-signed certificate of your HTTP proxy, you should be able to intercept HTTPS connections that would otherwise terminate. This is useful for fuzzing, analyzing, and testing iOS applications for security issues.

Source Reference : Click Here..

Thanks 🙂

Keep Coding and innovation new thing in your code … 😉

 

iDev : Essential Tools for iOS Developers

75 Essential Tools for iOS Developers

Source Reference : Here

If you were to go to a master woodworker’s shop, you’d invariably find a plethora of tools that he or she uses to accomplish various tasks.

In software it is the same. You can measure a software developer by how they use their tools. Experienced software developers master their tools. It is important to learn your current tools deeply, and be aware of alternatives to fill in gaps where your current ones fall short.

With that in mind, I present to you a gigantic list of tools. Some of these I use daily, others I see potential in. If you have more tools you’d like to see here, just make sure to add a comment.

I tried to categorize these the best I can. Some of the entries are websites, some are back-end services, but most are apps that you install. Not all of the apps are free, so I’ll make a note with a $ to denote that an app costs money.

And without further ado, we’ll start from the beginning of any project, and that

Inspiration

  • pttrns – A great library of iOS screen designs categories by task. If you want to see how other apps handle activity feeds, for instance, this is a great place to go see a bunch of examples.
  • TappGala – Another great collection of nice app designs. It’s not categorized by task, but is just a list of great apps to get inspiration from.
  • Cocoa Controls – A great list of components (code) that you can use in your iOS apps. Sometimes you’ll find great pieces of code that can save you time, other times you can just learn how other developers accomplish certain features. Subscribe to their weekly newsletter; all signal, little noise.
  • IICNS – A collection of really great icons. Get inspired, but don’t copy.
  • Dribbble – Some of the best digital designers post up their work for all to see. A treasure-trove of designs to look at.
  • Capptivate – a gallery of inspirational designs. Some contain animations. Thanks, @joaopmaia!

Design

  • Mocks ($) – An easy to use tool to create a quick mockup of an iOS app. Comes with a bunch of the default controls you can use to assemble something quickly.
  • Briefs ($) – A really useful app that allows you to create a mockup of an app and stitch them together so you can see the interaction. Deploy to a device so you can see what it feels like in your hand.
  • Acorn ($) – A strong competitor to Photoshop, only way cheaper. I find myself reaching for Photoshop less & less these days. Under active development.
  • Sketch ($) – A vector-based drawing tool that is increasingly useful these days, as screen sizes and pixel densities change. It is often helpful to design once and have the freedom to scale up & down as needed. Also sports a really powerful export system. For some example Sketch projects, check out Sketchmine. See my screencast on Sketch for a live demo.
  • iOS 7 PSD by Teehan+Lax – A super handy resource if you (or your designer) uses Photoshop. An iOS 6 version is also available.
  • Bjango’s Photoshop Actions – A definite time-saver if you use Photoshop to design iOS apps. One click access to resize canvases, scale by 200% (or 50%), set global lighting to 90º, and more. Their blog also has a bunch of useful Photoshop workflow tips.
  • xScope ($) – An indespensible swiss-army knife of tools such as guides, pixel loupes, screen rulers, and more. Want to know what color value that pixel is? Want to see how many pixels between a button and the window for a random Mac app? xScope has you covered. Also check out their companion iPhone app for mirroring designs you’re working on and seeing them in pixel-perfect glory on your iDevice.
  • Glyphish ($) – A fantastic collection of high quality icons for your iOS apps. Apple doesn’t provide a lot of built-in icons, so it’s handy to have a collection of icons covering all kinds of various concepts. I’m still looking for a use for that baby icon though. Glyphish comes in packs, and the latest pack has iOS 7 “thin line” icons which will be very handy when designing an iOS 7 app.
  • Fontastic Icons for iOS – An open source set of classes for utilizing icon fonts, such as Font Awesome in your iOS app. Quickly and easily have an icon in whatever pixel dimensions you require. Since fonts by nature can be scaled up and down with ease, this makes a really nice way to ship & use your icons without having to export multiple versions for the sizes you require.
  • PaintCode ($) – A vector-based drawing tool that exports your artwork as the equivalent Core Graphics source code. Awesome for learning how Core Graphics drawing works, but also incredibly handy if you want your drawing to be dynamic. See my screencast on PaintCode for a live demo.
  • Edge Insets ($) – A simple tool that helps you define your edge insets for repeatable images. Available on the Mac App Store.
  • LiveView – A remote screen viewer for iOS, making it easy to immediately see your designs on a device. Thanks, @_funkyboy!
  • Skala Preview ($) – Another excellent tool for quickly showing your designs off on a real device. The guys at Bjango are awesome and this app is deserving of the price. Thanks, jn40!

Source Control

  • Git – If you’re not using source control stop what you’re doing and rectify that. I use git for everything I do and love it.
  • Kaleidoscope ($) – The best diff/merge tool around. Does 3-way merges and is beautiful to look at. I use it every day.
  • p4merge – A free, ugly alternative to Kaleidoscope. Powerful 3-way merge, but good luck finding the download link. It’s hidden deeper in their site every time I look for it.
  • Git X – A simple, powerful GUI tool for visualizing git timelines and quickly & easily staging commits. I usually live in the Terminal for git usage, but fall back to this app when I need to stage hunks of changes into logical commits. This is a fork of the original (abandoned) GitX, which I found on this list of forks.
  • Source Tree – A free, full-featured Git application. I don’t use this because I favor the command line, but if a GUI tool is your cup-o-tea, check this app out.

Dissecting Apps

  • pngcrush – This little utility can crush & uncrush PNG files, which is handy when you want to view images contained in app bundled distributed in the App Store. Just open iTunes, view the local Apps list, and right click on any icon to Show in Finder. Once there, open up the app and you’ll see a bunch of PNG files, but you can’t view them. Using pngcrush you can extract the full version so it can be opened with Preview.
  • appcrush.rb – This handy little ruby script will automate the above process for all images. Just point it to a .app file on your disk and it will extract all the images to a folder on your desktop. Handy for seeing how apps on your phone accomplish certain designs. Check out my screencast on dissecting apps for a live demo.
  • Charles ($, free limited demo) – I don’t know what’s going on with the ugly UI or icon, but Charles is an essential tool for any developer. Charles acts as a proxy to allow you to inspect your network traffic to & from the iPhone Simulator. You can also inspect traffic from your device by setting your phone’s proxy to your Mac running Charles. With self-signed SSL certificates, request & response breakpoints, and request/response viewers, Charles is really amazingly powerful. A must-have tool. Again, my screencast on dissecting apps covers this well.

Editors

I know what you’re thinking, don’t all iOS developers use Xcode? Well mostly, yes. But with my love/hate relationship with Xcode, I believe there is tremendous value in considering alternatives.

  • AppCode – A full-fledged IDE from Jetbrains (makers of the excellent ReSharper for .NET). Immensely powerful refactorings & features that help you write code faster. Quickly identify dead code, automatically insert #import statements when you use related code, easily extract variables, methods, and classes. My only wish for this app is that it would instead be a plugin to Xcode.
  • Vim – Wait, vim? Really? Yes, there are folks who do all their Objective-C development in vim. I’m not one of these, but I am a fan of vim for Ruby development. As such, I’m a huge fan of…
  • Xvim – An Xcode plug-in that gives you vim keybindings. Works well, ‘nuff said.
  • OMColorSense – Another plugin for Xcode, this one gives you a small display of color when your cursor is on a line looking like: [UIColor redColor]. Clicking on this little color tab opens a color picker that you can change, and any change in color you make is reflected in the code by changing the line to [UIColor colorWithRed:… green:… blue:… alpha:… ]. When someone is watching me write code with this enabled, they invariably ask me, “Whoa! What was that?!”
  • KSImageNamed – Another Xcode plug-in, this one allows you to autocompleted image filenames from your bundle when typing [UIImage imageNamed:…]. Great way to avoid the inevitable typo that causes this method to return nil and you to subsequently waste 10 minutes trying to figure out why your images aren’t displaying.
  • CocoaPods Xcode Plugin – This plug-in adds a menu item for interacting with CocoaPods. Useful if you don’t like dropping to the command line.
  • Alcatraz Package Manager – An awesome meta plug-in that allows you to easily install other Xcode color schemes and plug-ins with a single click.
  • Code Runner ($) – a light-weight code-aware text editor that knows how to compile & run code in most languages. Want to test out a quick snippet of Objective-C code and don’t want to create an entire Xcode project to do it? Code Runner to the rescue.

Documentation

Ahhh, documentation, everyone’s favorite topic. Even still, documentation is really important to have, so pay attention so we can make your life easier.

  • appledoc – Want to automatically generate documentation that look’s like Apple’s? Look no further. Automatically inter-links symbols defined in your project as well as extracting discussion to output using specially formatted code-comments. Generates official docsets and HTML web sites.
  • Dash ($) – A must-have API documentation viewer and code snippet manager. This tool is really handy as it allows you to download & search API docs for all kinds of languages & frameworks with lightning speed. The fastest way to get access to the docs. I integrate Dash with Alfred to make searches even faster.

Dependency Management

Yes, there’s only one tool listed here. I didn’t want to include actual 3rd party libraries, as that would be a different list entirely. When it comes to dependency management, there’s only one game in town:

  • CocoaPods – The essential tool for Objective-C projects. Allows you to quickly & easily integrate 3rd party libraries into your application. It does so by creating a second static library project and automatically links this with your projects. There are thousands of pods available, and it’s easy to add support for libraries that you don’t own (or perhaps are private). I use CocoaPods in every single project I work on.

Diagnostics & Debugging

At some point our app is in the field and we need to understand better what’s going on, maybe to fix bugs or to improve performance.

  • Cocoa Lumberjack – a much more powerful NSLog, Cocoa Lumberjack offers advanced logging behaviors such as logging to rotated files, logging to the network, and filtering based on log level (info, debug, warn, error). Covered by NSScreencast Episode 61
  • DCIntrospect – crazy powerful tool that you’d link inside your app when running in debug and on the simulator. Once you do, you can press the spacebar to get some really helpful view debugging support. See exact dimensions of elements on the screen, print out view hierarchies, even nudge views horizontally or vertically.
  • Pony Debugger – another tool you’d use by embedding a library in your debug builds, Pony Debugger actually utilizes Chrome’s dev tools for seeing network requests coming out of the device, as well as a rudimentary Core Data browser. It’s hard to describe, but check out my screencast on Pony Debugger for more info.
  • Runscope ($) – Runscope is a service running online that can capture requests, log details, and give you valuable data about your API. Simple to set up, as it’s an HTTP pass-through API, all you need to change is your host name.
  • SimPholders – Quick, easy access to your simulator folders. Browse by iOS version, then app name and jump right to the folder in Finder.
  • Spark Inspector ($) – Debug your view hierarchy running on your app in debug mode, in 3D. This app really has to be seen to fully understand the value, but it can really help to understand what views are used to compose your app. Also contains a notification center inspector, so you can easily see what NSNotifications are firing and who is observing them. Another app to look at that is similar is Reveal.

Images

  • ImageAlpha – A Mac app that allows you to convert a 24-bit PNG with transparency to an 8-bit PNG with an alpha channel. Typically 8-bit PNGs don’t have an alpha channel, so if your image can be represented in 8-bits (say, a solid color button) you can save a lot on storage by converting the 24-bit PNG to 8-bit using ImageAlpha.
  • ImageOptim – Another Mac app that compresses PNGs in order to save space. Most PNG files can shave off a few % of the size, and sometimes you’ll shrink the files by 30% or more. Smaller images mean smaller app sizes and less memory used to load them at runtime.
  • Prepo – A little Mac app that can quickly resize artwork in all the various sizes you might need. Just drag a large icon file (say, 1024×1024) onto Prepo and watch it spit out 512×512 iTunesArtwork, 114×114 Icon@2x.png, and all the other sizes & filenames you’d expect.
  • Slender ($) – an awesome app that analyzes your app and finds all sorts of problems, such as missing retina artwork, unused images, image that could benefit from compression and more. Shave kilobytes off of your iPhone app by shedding unused images with Slender.

Core Data

  • Mogenerator – still a super useful tool for generating smart subclasses of your NSManagedObjects in your Core Data model. Some use Xcode for this, and resort to manually subclassing or creating categories in order to add logic to the models. Mogenerator runs as a quick pre-compile script to generate subclasses for you to use. It does this by creating an underscored version (_User) and a regular one for you to modify (User).
  • Base ($) – there will come a time when you need to inspect your actual Core Data sqlite database to see what’s going on. You can use the sqlite3 command line tool, but Base offers a nice looking GUI browser. Just don’t vomit when you see the database schema that Core Data created for you.
  • Core Data Editor ($) – for more advanced data anlysis, exploration, and modification you can use Core Data Editor. This app understands Core Data, so you’re working directly with the entities instead of database rows.

Back-end Services

Ultimately your iOS app will likely want to talk to a server to share data, fetch new content, send push notifications or whatever. While this can be accomplished manually, you might want a more drop-in solution.

  • Helios – Helios is an open-source framework that provides essential backend services for iOS apps, from data synchronization and push notifications to in-app purchases and passbook integration. Built on top of many open source ruby gems, so you can pick & choose and build your own stack if you so desire. Take a look at the Nomad CLI set of handy related tools as well.
  • Windows Azure Mobile Services – you can think of this sort of like a programmable database in the cloud. Create tables, run JavaScript on read, insert, delete to add additional functionality. Really easy support for push notifications as well.
  • Urban Airship – I’ve been using Urban Airship to deliver push notifications for a while now. Really easy to integrate with, and small usage is free.
  • Parse – This is another data-in-the-cloud service, but offers an impressive API and online data browser. We use Parse for a really small app and works well for that.

Analytics

There are other players here, but none that I’ve seen have been compelling enough to switch from flurry. I’m open to hearing suggestions, so let’s hear about ‘em in the comments.

  • Flurry – I’ve used flurry for a long time to provide useful analytics on the usage of my apps. Need to know when to stop supporting iOS 5? Flurry gives you the numbers to have a realistic conversation.

Deployment

  • Deploymate ($) – Need to support iOS 4 still, but you’re compiling with the iOS 6 SDK? Deploymate will warn you when you’re using symbols that don’t exist in your deployment target.
  • Cupertino – Part of the Nomad CLI tools, Cupertino gives you command line access to managing devices & profiles in the Apple Provisioning Portal. For example, just type ios devices:list to see the current list of devices in your account. Useful for automating lots of processes.
  • Hockey App ($) – A great service for managing the distribution of your ad-hoc builds. Testers can get a link to install new betas over the air. Also provides robust crash reporting so you can easily respond to crashes in your apps.
  • TestFlight – A free service, similar to Hockey App. We’ve used TestFlight with great success for easily distributing apps and collecting feedback from our users. My only wish is that they’d start charging for the service. Also includes analytics and crash reporting, but we don’t use those features.
  • iOS Simulator Cropper – A really easy way to snap images of the simulator, with or without status bar, with or without device chrome, etc. Great for taking App Store or just general marketing screenshots.
  • Status Magic ($) – Take better app store screenshots. Nothing makes your app look less crappy than an App Store screenshot that includes a low battery, or low signal. Status Magic gives you complete customization over what’s present in your status bar, including removing elements, changing the time to “9:41 AM” like Apple tends to do, and more.
  • Crashlytics – Excellent crash reporting for your apps in the field. Automatically uploads dSYMs on release builds so your crashes are automatically symbolicated and organized for you to focus on the most critical ones.

Testing

I don’t think we as a community focus enough on testing. There are great tools available to us, and most are so easy to use we have no real excuse not to write at least some tests for our apps.

  • Kiwi – A great Rspec-style testing framework for iOS. Built on top of SenTestingKit, so you just type ⌘U to run your specs. Also includes a completely robust mocking & stubbing library as well as assertions.
  • Specta – A light-weight BDD framework very similar to Kiwi, but the expectation syntax has one major benefit over Kiwi: everything is implicitly boxed like this: expect(items.count).to.equal(5). There’s no need to wrap 5 in an NSNumber like Kiwi does. Use in conjunction with Expecta for a bunch of useful matchers.

The following are all various ways of performing end-to-end acceptance tests. These tests will actually interact with your interface, touching buttons, scrolling, etc. By nature these will be slower and more brittle, but testing in broad strokes is certainly helpful to see if all of the pieces fit together properly.

Demos / Marketing

  • Reflector ($) – Wirelessly mirror your iOS device on your Mac using Air Play. Great for doing demos of applications on your computer.
  • Placeit – A great collection of high res photos of people using devices, but the screens are templates that you can insert your own screenshots into. Very cool, and great for displaying your app in a nice way on your website.

App Sales Reporting

Of course you want to be able to see how much money you’re making on your app, right? There are a few solutions for this, but here are a couple that work well:

  • App Viz 2 ($) – a really useful Mac app for tracking sales of your apps. You run it locally and it logs in and downloads your sales reports.
  • App Annie – an online sales reporting tool. I’m less comfortable giving my credentials to iTunes to a 3rd party, but it does keep the reports up to date for you so you don’t have to run an app locally. In the comments, Josh Brown suggests creating a different user for analytics in iTunes Connect, which is a really good idea.

Grab Bag

These tools don’t have a defined category above, but deserve a mention nonetheless.

  • Quick Radar – Submitting bug reports to Apple is our only way of making their tools better. If you’re frustrated by the lack of a feature, you should be submitting a bug report. If you come across a bug, you should be submitting a bug report. One has no right to complain if they have not yet filed a radar :). With that in mind, submitting bug reports via bugreporter feels like a trip back to 1995. Quick Radar is an awesome little app that makes submitting bug reports super easy. Sports automatic posting to open radar so others can see it, in addition to tweeting, and posting to App.net. I use this app several times per week.

Thanks 🙂

Keep Reading and Experiment on your code….

 

iDev : Create, Rename, Delete, Read and Write File on iOS Functions

Hi Friends,

On iOS Programming, one of the most frequent tasks is Manipulation with Files. Using Local Files is one of the most efficient way to store your local data, other ways may include NSUserDefault, Core Data, but local files is very easy to be implemented and organized. So in this tutorial, we will focus on 5 main manipulation related to Local File on iOS.

Before we get started, we first should know what files have been stored in your app’s sandbox. As you might know, every app on iPhone is like an island, usually we name it SandBox. It contains AppName.app, Library folder, tmp folder and Document folder. User usually have their data stored in Document folder if they choose to use local file to store their data because other folders are not designed to store user’s data. So here we use Document Folder to give our test.

So, let’s list all the files exists in Document Folder in our Sandbox.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)listAllLocalFiles

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

// This function will return all of the files’ Name as an array of NSString.

NSArray *files = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];

// Log the Path of document directory.

NSLog(@”Directory: %@”, documentsDirectory);

// For each file, log the name of it.

for (NSString *file in files) {

NSLog(@”File at: %@”, file);

}

}

1, Create a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)createFileWithName:(NSString *)fileName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

NSFileManager *manager = [NSFileManager defaultManager];

// 1st, This funcion could allow you to create a file with initial contents.

// 2nd, You could specify the attributes of values for the owner, group, and permissions.

// Here we use nil, which means we use default values for these attibutes.

// 3rd, it will return YES if NSFileManager create it successfully or it exists already.

if ([manager createFileAtPath:filePath contents:nil attributes:nil]) {

NSLog(@”Created the File Successfully.”);

} else {

NSLog(@”Failed to Create the File”);

}

}

2, Delete a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

– (void)deleteFileWithName:(NSString *)fileName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

NSFileManager *manager = [NSFileManager defaultManager];

// Need to check if the to be deleted file exists.

if ([manager fileExistsAtPath:filePath]) {

NSError *error = nil;

// This function also returnsYES if the item was removed successfully or if path was nil.

// Returns NO if an error occurred.

[manager removeItemAtPath:filePath error:&error];

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, fileName);

}

}

3, Rename a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];

NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];

NSFileManager *manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePathSrc]) {

NSError *error = nil;

[manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, srcName);

}

}

4, Read a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/* This function read content from the file named fileName.

*/

– (void)readFileWithName:(NSString *)fileName

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePath]) {

// Start to Read.

NSError *error = nil;

NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:&error];

NSLog(@”File Content: %@”, content);

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, fileName);

}

}

5, Write a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

/* This function Write “content” to the file named fileName.

*/

– (void)writeString:(NSString *)content toFile:(NSString *)fileName

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

// Check if the file named fileName exists.

if ([manager fileExistsAtPath:filePath]) {

NSError *error = nil;

// Since [writeToFile: atomically: encoding: error:] will overwrite all the existing contents in the file, you could keep the content temperatorily, then append content to it, and assign it back to content.

// To use it, simply uncomment it.

//        NSString *tmp = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:NSStringEncodingConversionAllowLossy error:nil];

//        if (tmp) {

//            content = [tmp stringByAppendingString:content];

//        }

// Write NSString content to the file.

[content writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&error];

// If error happens, log it.

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

// If the file doesn’t exists, log it.

NSLog(@”File %@ doesn’t exists”, fileName);

}

// This function could also be written without NSFileManager checking on the existence of file,

// since the system will atomatically create it for you if it doesn’t exist.

}

Appending the file and add another text continously used this on Write menthod

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *docPath = [documentsDirectory stringByAppendingPathComponent:@”File.txt”];

NSString *appendString = //Your appending string ;

NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:docPath];

[myHandle seekToEndOfFile];

[myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];

Also, similar API applies to URL and Directory. Check Apple’s Doc for more details.

iDev: UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

While working on a particular UISearchBar I ran into 2 little problems, both easy to fix but I thought of posting them in case someone is stuck. What I needed was to make the cancel button and the scope bar to be displayed only while editing. I believe that this should be a pretty common thing to do, and the first part is pretty straight forward:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = YES;

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = NO;

return YES:

}

That is pretty simple, specially if you don’t forget to associate the UISearchBar’s delegate!

Next, I tried the same with the scope bar but it didn’t work – the scope bar wouldn’t appear. During my testing, I tried to start with the scope bar displayed and then hiding it after the first edit… it worked but when disappearing the search bar would preserve the height as if it was still showing the scope bar!

The final solution is a simple call to [searchBar sizeToFit] and everything works as smooth as it should. Here is the complete code with the small bonus of animating the cancel button’s (dis)appearance:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = YES;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:YES animated:YES];

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = NO;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:NO animated:YES];

return YES;

}

iDev: Design pattern are used on iOS Development other than MVC

Hi Friends,

Here the some list of design pattern with sort description

Image

What is Design Pattern?

A design pattern is a common solution to a software problem. They are helpful for speeding up problem solving, ensuring
that a developer doesn’t have to re-invent the wheel for every situation. They also give developers a common vocabulary with which to get across high-level ideas with minimal explanation and full understanding.

Design patterns are everywhere in iOS Developement,Because iOS is a fairly specific platform, developers often face similar problems over and over, so there are a few design patterns that are extremely common in iOS.

Here is a short list of design patterns used by software engineers:

  • Abstract Factory Pattern
  • Adaptor Pattern
  • Object Modeling Pattern
  • Chain of Responsibility Pattern
  • Command Pattern
  • Composite Pattern
  • Decorator Pattern
  • Façade Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Memento Pattern
  • Model-View-Controller Pattern
  • Observer Pattern
  • Proxy Pattern
  • Receptionist Pattern
  • Singleton Pattern
  • Template Method Pattern
  • S.O.L.I.D. Programming

On iOS :

Abstract Factory

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. The client is decoupled from any of the specifics of the concrete object obtained from the factory.

Adapter

The Adapter design pattern converts the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. It decouples the client from the class of the targeted object.

Chain of Responsibility

The Chain of Responsibility design pattern decouples the sender of a request from its receiver by giving more than one object a chance to handle the request. The pattern chains the receiving objects together and passes the request along the chain until an object handles it. Each object in the chain either handles the request or passes it to the next object in the chain.

Command

The Command design pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. The request object binds together one or more actions on a specific receiver. The Command pattern separates an object making a request from the objects that receive and execute that request.

Composite

The Composite design pattern composes related objects into tree structures to represent part-whole hierarchies. The pattern lets clients treat individual objects and compositions of objects uniformly. The Composite pattern is part of the Model-View-Controller aggregate pattern.

Decorator

The Decorator design pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. As does subclassing, adaptation of the Decorator pattern allows you to incorporate new behavior without modifying existing code. Decorators wrap an object of the class whose behavior they extend. They implement the same interface as the object they wrap and add their own behavior either before or after delegating a task to the wrapped object. The Decorator pattern expresses the design principle that classes should be open to extension but closed to modification.

Facade

The Facade design pattern provides a unified interface to a set of interfaces in a subsystem. The pattern defines a higher-level interface that makes the subsystem easier to use by reducing complexity and hiding the communication and dependencies between subsystems.

Iterator

The Iterator design pattern provides a way to access the elements of an aggregate object (that is, a collection) sequentially without exposing its underlying representation. The Iterator pattern transfers the responsibility for accessing and traversing the elements of a collection from the collection itself to an iterator object. The Iterator defines an interface for accessing collection elements and keeps track of the current element. Different iterators can carry out different traversal policies.

Mediator

The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. These objects can thus remain more reusable. A “mediator object” in this pattern centralizes complex communication and control logic between objects in a system. These objects tell the mediator object when their state changes and, in turn, respond to requests from the mediator object.

Memento

The Memento pattern captures and externalizes an object’s internal state—without violating encapsulation—so that the object can be restored to this state later. The Memento pattern keeps the important state of a key object external from that object to maintain cohesion.

Observer

The Observer design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The Observer pattern is essentially a publish-and-subscribe model in which the subject and its observers are loosely coupled. Communication can take place between the observing and observed objects without either needing to know much about the other.

Proxy

The Proxy design pattern provides a surrogate, or placeholder, for another object in order to control access to that other object. You use this pattern to create a representative, or proxy, object that controls access to another object, which may be remote, expensive to create, or in need of securing. This pattern is structurally similar to the Decorator pattern but it serves a different purpose; Decorator adds behavior to an object whereas Proxy controls access to an object.

Receptionist

The Receptionist design pattern addresses the general problem of redirecting an event occurring in one execution context of an application to another execution context for handling. It is a hybrid pattern. Although it doesn’t appear in the “Gang of Four” book, it combines elements of the Command, Memo, and Proxy design patterns described in that book. It is also a variant of the Trampoline pattern (which also doesn’t appear in the book); in this pattern, an event initially is received by a trampoline object, so-called because it immediately bounces, or redirects, the event to a target object for handling.

Singleton

The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.

Template Method

The Template Method design pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Source: Cocoa Design Patterns.

Reference : Stackoverflow.

Image

Thanks 🙂 Keep Coding…

iConcepts: 12 Myths About Concurrency in Objective-C By Jiva

12 Myths About Concurrency in Objective-C By Jiva 

There’s lots of cases where new Objective-C programmers incorrectly apply threads or misunderstand their use. I often see code from well intentioned folks who use threads where they absolutely don’t need them. Consequently, I thought I would put together this list of 12 myths to help guide you along the way to the proper use of threads in your apps.

Myth #1: Threads will make my app faster!

This is probably the most common newbie programmer mistake. Thinking that threads will make your app faster.

They won’t. Your code will execute at exactly the same rate regardless of whether it’s threaded or not. The key advantage that threads provide is that, in the case of a multiple-core machine, they allow you to do two things at once. This can speed processing of certain operations, but only in cases where the different operations are parallelizable. That is, in cases where the operations do not rely on each other for any portion of their calculations.

Even in cases where your operations are parallelizable, if you do not have multiple cores, your code will actually run slower if you add threads, since the processor will be doing more context switches to handle your threads.

https://i2.wp.com/www.random-ideas.net/Dropbox/Threading.png

So, in fact, the cases where threading will actually improve the performance of your app are confined to a relatively small subset. Still, this subset is important and encompasses many common use cases. Unfortunately, too often threads are applied in areas where they are not needed and where they will not significantly improve performance. The effort required to get threaded code right is substantial, and you need to weigh the benefit to bullshit ratio involved. You should also always profile your app before adding threads. You may find that the use case which you think is causing you problems in fact is not. Measure twice and cut once.

Myth #2: Threads will make my code simpler.

Writing thread safe code is hard. It’s seductive to think that if you could spin specific operations off into background threads, they become easier to manage because you no longer have to deal with things like callbacks, and asynchronicity.

The fact is, that adding threading to a complex app will only make it much, much more complicated. There’s an old saying that goes:

Without threads you have n problems. But with threads you have n+1 problems.

Or, as I like to say:

With threads you have n! problems!

Not only will you still have to deal with all your normal coding problems, you’ll also have to deal with things like locking, synchronization, queuing changes. Your code really becomes a lot more difficult to manage when you add threads.

Myth #3: I need threads to solve my problems with blocking I/O.

This common misconception comes from the fact that there are several synchronous methods on some of the foundation classes such as NSString and NSData which allow you to download content from the Internet. These methods, such as+stringWithContentsOfURL: are tremendously convenient, but block the current thread. Using them is as simple as:

NSString *myStr = [NSString 
                     stringWithContentsOfURL:urlToMyData];

Obviously, you’d never want to block the main thread, so a conscientious coder will often (wrongly) imagine that spinning this operation off into a background thread is a good way to still use these convenient methods. The fact is that this is a bad idea.

Threads can only be terminated when they are checking some kind of control variable and can thus be triggered to exit, such as:

while(keepRunning)
{
    NSString *myStr = [NSString 
                     stringWithContentsOfURL:urlToMyData];
}

Since the +stringWithContentsOfURL method blocks, the keepRunning variable will never get checked. So how do you stop this thread? The fact is, you don’t. There is simply no way to terminate a blocked thread.

This issue alone should be enough to make you walk away, but in case its not, consider that you also have no way to specify a timeout for these methods, you can no longer properly handle complex handshaking such as from authentication, and you lose the ability to interpret status codes that might be returned when accessing the resource.

Because of all this, you should never use these methods.

You might be saying to yourself right now “But I don’t need to worry about those things, I have a very simple use case, and my data will always be available.”

The answer is no. Never use these methods! there’s no need to! The Foundation classes, NSURLConnection and NSURLRequest provide more than enough functionality to do the job properly without blocking and without using threads.

Before I came to Objective-C I wrote a lot of C++, most of it networking code. I know how hard it is to get networking code right. One surprising lesson I learned is that even when writing services that had to handle many incoming connections, threads are almost always still the wrong answer. If you imagine a case where you’re handling hundreds of connections, you really don’t want to spawn and manage hundreds of threads. You’re really much better treating your sockets as a pool and handling I/O on them that way.

Much research has been done on this subject, but one of the best resources I have found is from Dan Kegel in his article, “The C10K problem.” You can go read those docs, and bleed yourself into socket code for the next 5 years of your career, or you can take my word for it: Apple knows what they’re doing here, and they got it right.NSURLConnection and NSURLRequest will handle 90% of the networking needs of most developers.

(How to handle the other 10%? That’s another post!)

A lot of developers will also make the mistake of prematurely optimizing networking code like this when they have large resources they have to download. They imagine that they need to run even NSURLConnection in a background thread. This couldn’t be further from the truth.

NSURLConnection is extremely efficient at downloading even very large files. I’ve never seen a file it couldn’t handle. It will not block your runloop. Your own code, processing those large files, may block the runloop and need to be threaded, but the actual downloading will not.

Myth #4: NSOperation means I don’t have to think about threading issues.

Just because you’re using NSOperation doesn’t mean your code is magically thread safe. NSOperation provides no thread safety facilities whatsoever. It simply provides an easier way to spawn and manage threads by abstracting away the details of the thread itself. All you need to provide is the code that actually does the work. NSOperation does the rest for you.

What this means in terms of our discussion here is that everything I’ve said about writing thread safe code still applies and code you write as part of your NSOperations still needs to be thread safe.

Myth #5: Atomic properties makes my code thread safe

As we’ve already seen, thread safety is a complex subject full of dark alleys and pitfalls. At it’s most fundamental level, even just reading a value from memory can be fraught with peril. When making your classes thread safe, you have to account for both these low level fundamental operations as well as higher logical level relationships, such as setting different variables within your class.

Atomic properties addresses only the issue of accessing your property values. An atomic property insures that the setter of a property cannot modify the property while it is being retrieved. Basically, when you use atomic properties, the accessors generated by the compiler wind up looking something (roughly) like the following:

 //@property(retain) UITextField *userName;
 //Generates roughly

 - (UITextField *) userName {
     UITextField *retval = nil;
     @synchronized(self) {
         retval = [[userName retain] autorelease];
     }
     return retval;
 } - (void) setUserName:(UITextField *)userName_ {
     @synchronized(self) {
       [userName_ retain];
       [userName release];
       userName = userName_;
     }
 }

(via objective c – Atomic vs nonatomic properties – Stack Overflow)

When using an atomic property, you will never run into the circumstance where you receive a corrupt value from the getter due to the setter changing the value while you are getting it. This doesn’t mean that the setter won’t change the value after you have received it, and so, thus, it does not fully insure thread safety. It only addresses one part of the full thread safety picture.

Myth #6: Serial operation queues are not threaded.

Just because you’ve made an NSOperationQueue serial by setting it’smaxConcurrentOperationCount to 1 doesn’t mean that the operations you add to that queue will not be run in a background thread. In fact, with the exception of the built-in queue you get from the NSOperationQueue class method, +mainQueue(NSOperationQueue Class Reference) all queues will run in a background thread. In the case of the +mainQueue it actually returns the queue associated with the main thread of your application and runs it on that queue. The main queue is serial.

Myth #7: GCD makes threading easy.

Along these same lines, GCD also does not make working with threads any safer or easier than any other thread mechanism. GCD’s role in Objective-C threading is actually for the purposes of managing thread pools. It’s job is to correctly determine the appropriate number of threads to use for your hardware based on the number of processors and cores your machine has. Although you can use the low level GCD API to add your operations directly to GCD, NSOperation provides a higher level abstraction to the very same mechanism, and is, generally, the preferred way to do it.

Myth #8: Threads Can Be Terminated Safely From Outside The Thread

It’s actually not possible to terminate a thread if the thread itself doesn’t want to be terminated. This is not entirely obvious, but it’s true. This is why most threaded operations utilize a flag to tell them when to exit prematurely. For example:

-(void)myThreadedOperation
{
    while(continueToRun && ![self allStuffIsDone])
    {
        // do some stuff...
    }
}

In this case, we have a background thread that is doing a series of operations. When all the operations are done, it sets the returns true from -allStuffIsDone and exits the loop. However, it also has a flag called continueToRun which its checking on each loop. This flag can be set by an external thread to cause this thread to exit after any iteration. If your background operations will take a long time, you probably want to include a similar design pattern.

Myth #9: I can safely throw exceptions in threads.

What happens when an exception is thrown in Objective-C and not caught? Usually, a crash. 1 What happens when an exception is thrown in a background thread and not caught? The answer is, the one thing worse than a crash: undefined behavior. It might crash… It might crash the whole app… It might crash just the thread… No one knows! It’s undefined. Your thread might even crash, and your app continue running. What do you think your app will do if it expected that thread to later either still be running or have finished?

Although I wouldn’t say that you can’t throw exceptions in threads at all, the important thing to know is that if you do, and it doesn’t get caught, the end result for your app is very bad.

Fortunately, Objective-C doesn’t use a lot of exceptions. So I don’t advocate putting generic exception handlers at the top of all your threaded operations. I point this out more as a “thing to know”. That exceptions can be dangerous in threads, and to be careful when working with code that does throw exceptions.

Myth #10: I can update my gui from background threads.

This one is fairly well known, but worth mentioning anyway. Cocoa and CocoaTouch, the GUI frameworks used on Mac OS and iOS respectively, are not thread safe. You must never update your GUI from a background thread. Whenever you need to trigger a GUI update from a background thread, you should do so on the main thread. Here’s an example of how to do this using the main queue and a block:

[[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        [self.tableView reloadData];
    }];

Myth #11: Notifications from background threads are executed on the main thread.

Notifications are nothing more than a set of method calls. So when a notification occurs, your notification handler will be called from the thread upon which the notification was triggered. This has some interesting implications.

For example, when you’re saving Core Data objects in a background thread, this notification will be sent from that background thread. Ordinarily, this is a great notification to watch for to update your UI when changes occur. Of course, we already talked about how you can’t update your UI from a background thread, but in addition to this, most of Core Data itself is also not thread safe2. In this case, the objects sent with the notification using the NSInsertedObjectsNSUpdatedObjects, andNSDeletedObjects keys in the userInfo dictionary cannot cross threads, so you can’t use them directly, even if you forward the notification to the main thread.

To handle this problem, you need to use the NSManagedObjectContext method, -mergeChangesFromDidSaveNotification: in the thread of the context which is receiving the notification so it can merge the changes. To do this, you can use themainQueue again like I showed you before:

[[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        [self.ctx mergeChangesFromContextDidSaveNotificaton:
                                     inNotification];
    }];

Myth #12: I shouldn’t use threads

Given all these hazards, you might think that you should never use threads. This is not the case. Threads are a useful tool, but like any tool, they have to be respected.

Threads are like the tablesaw of the Objective-C wood shop. They cause more application injuries than all other technologies combined. There’s times, however, when they’re really the best tool for the job! The important things to remember when using threads are:

  • Keep your thread’s data isolated.
  • Simplify the algorithms you intend to use in threads. Make them the “simplest thing that can possibly work.”
  • Learn the API used for insuring thread safety like it’s the back of your hand. Things like NSLock, @synchronized, NSRecursiveLock, etc.

  1. You can install an unhanded exception handler to change this behavior. 
  2. NSManagedObjectContext for example, can’t cross threads either. This is probably worthy of a post all of it’s own someday! 

Reference : Go Here

iDev: Getting Started with iOS 7 (Design Icon)

Image

At the keynote Apple event on September 10, 2013, the company not only unveiled their newest iPhones, but they formally announced iOS 7, the latest version of the operating system which drives all Apple mobile devices. It’s scheduled to roll out to the public on Wednesday, September 18 (tomorrow!) and it brings with it a few things that Corona developers should be aware of.

First and foremost, your existing iOS 6.1 and earlier apps should run without any problems. There are, however, a few things that your Corona-built apps must have to behave properly on iOS 7.

App Icons

In iOS 7, Apple has added a few new icon sizes, effectively increased by a few pixels in each of the core usage cases. Of course, you should still support iOS 6.1 and earlier, so the previous icon sizes remain valid and necessary. The questions that arise in regards to iOS icons include:

  • What size(s) are the required icon image files?
  • How must I name these icon image files?
  • Does each icon image file need to be named exactly and specifically?
  • Do they have to be listed in the build.settings file, and if so, where?

Let’s answer these questions now. Since iOS 3.2, Apple has used a plist in the bundle information calledCFBundleIconFiles. This is an array of strings equating to the names of the icons used in your app. For the most part, the naming scheme is fairly flexible, which creates some confusion about exactly how the icons should be named.

To keep this simple for Corona developers, you need to add 4 new required icons and 2 new  recommendedicons, for a total of 6 new image files. Remember to place these files inside your core project folder, not inside a subfolder.

Icon Purpose Recommended Name Size Required
iPhone/iPod Icon-60.png 60×60 Yes
iPhone/iPod (Retina) Icon-60@2x.png 120×120 Yes
iPad 1/2, iPad Mini Icon-76.png 76×76 Yes
iPad 3/4 (Retina) Icon-76@2x.png 152×152 Yes
Spotlight/Settings Icon-Small-40.png 40×40 Recommended
Spotlight/Settings (Retina) Icon-Small-40@2x.png 80×80 Recommended

To minimize changes in your code, we recommend keeping the existing icon file names that you use today, then simply add these new ones to the mix. Your new build.settings file would then contain:

settings =
{
   iphone =
   {
      plist =
      {
         CFBundleIconFiles = {
            "Icon.png",
            "Icon@2x.png",
            "Icon-Small-40.png",
            "Icon-Small-40@2x.png",
            "Icon-60.png",
            "Icon-60@2x.png",
            "Icon-72.png",
            "Icon-72@2x.png",
            "Icon-76.png",
            "Icon-76@2x.png",
            "Icon-Small-50.png",
            "Icon-Small-50@2x.png",
            "Icon-Small.png",
            "Icon-Small@2x.png"
         },
      }
   },
}

Please refer to our Project Build Settings guide for a complete list of the required icon sizes. Many of you may not be including the smaller settings/spotlight search icons.

NOTE: Although this is an iOS-related post, we’ve also added a quick Android update as of Daily Build #1206. Specifically, the new Android xxhdpi.png icon is now supported in Corona, so you should include it if you’re publishing to Android. This new icon size is 144×144 pixels in size — conveniently the same as the iOS Icon-72@2x.png file.

Styling Apps For iOS 7

Perhaps the biggest change in iOS 7 is a completely new look and feel. Apple has “flattened” the interface considerably, steering away from that “real world” look known as skeuomorphic. In other words, buttons don’t need to look like physical buttons to be functional. If you’re a fan of skeuomorphic designs, like a compass app that looks like an actual compass, iOS 7 may not appeal to you visually. However, for those who hate skeuomorphic design (a calendar app doesn’t really need a “spiral binding” after all), Apple has sided with the “less UI is more” team.

In the world of games, this is probably going to have very little impact on your development. However, in the business and utility world, there is a strong, industry-wide movement to flatten designs and move away from skeuomorphism.

For developers using Corona’s current widget library, set to the default iOS theme, you know that the widgets resemble the native widgets in iOS 6.1 and earlier. Now, for those who are eager to begin styling their apps for iOS 7, we have added an iOS 7 widget theme as of Daily Build #1206. To use it, simply include this line of code after you require the widget library:

local widget = require( "widget" )
widget.setTheme( "widget_theme_ios7" )

One current exception is the picker wheel widget. Native iOS 7 uses some 2.5D visualizations wherein the top and bottom of the wheel is skewed slightly to provide a sense of depth. We’ll add this to the Corona picker wheel widget when Graphics 2.0 is officially released, but for now your picker wheels will appear flat.

Fonts

The new font for iOS 7, in most cases, is Helvetica Neue Light. If you want to build apps that match iOS 7 in typography, you’ll probably want to use this font as well, for example:

local myButton = widget.newButton{
   left = display.contentCenterX - 100,
   top = 360,
   label = "Send Message",
   width = 200, 
   height = 48,
   font = "HelveticaNeue-Light",
   onEvent = onButtonEvent
}

Fortunately, this font is included in both iOS 6 and iOS 7, as well as on OS X. If you want a bolder version, just use“HelveticaNeue”. If you need a template for iOS 7 imagery, an Adobe Photoshop PSD of graphical elements is located here — just make sure that you read and understand the legal usage terms that accompany this download. Finally, a good article that describes Apple’s requirements and recommendations is located here.

Building for iOS 7

Public Build #1202 can only build for iOS 6.1 and earlier, but Daily Builds after that have an additional dialog option called iOS SDK which we include at any time there are two versions of the iOS SDK to build for. As of Daily Build #1203, choosing iOS 7 will build against the “iOS 7 Gold Master seed.” This means that you can submit builds to Apple using this option. Daily Build #1203 – #1206 lists this as a “Beta” but it is the GM seed, not one of the Beta versions.

While we are using the iOS 7 GM seed SDK, it’s still in testing mode. We are working out the last few details before we enable app submission against the iOS 7 target. However, you should be testing against it, and there are a few other software requirements before you can do so:

  1. Building for iOS 7 requires XCode 5. Apple made XCode 5 available today in the Mac App Store as a free download. This will install over top of your existing Xcode 4.x installation.
  2. You must be running OS-X Mountain Lion (10.8) or later to run XCode 5.

If you have been running the XCode 5 developer preview, but you need to revert back to building with 4.x or if you want to use the XCode 5 GM Seed, you’ll need to specify so using the following command line (Terminal) command:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

In Summary

iOS 7 brings a fresh new look to iOS, while at the same time introducing many new features and UI improvements.

Reference: Here

Thanks 🙂 Keep Coding 🙂

iDev : Experiments with precise timing in iOS

Experiments with precise timing in iOS

iOS is by no means a realtime operating system, but I’m aware that NSTimer and NSObject’sperformSelector:withObject:afterDelay: mechanism aren’t particularly accurate, and I was curious to see whether I could do better.

Hands up, backing away

Disclaimer: I am not at all an expert in realtime programming, or Mach, or iOS-device optimisation, so this is pretty much a fumble in the dark. I won’t be at all offended if anyone wishes to shoot me down and offer a more sensible solution — in fact, please do! Until then, watch as I stumble on…

Also note that there are often ways to eliminate the need for precise timing of this nature, by architecting code appropriately — when it comes to audio, for example, CoreAudio provides a very accurate time base in render callbacks. For things like metronomes or audio synthesizers, it’s always better to establish a starting time, and use the difference between the current time and the starting time in order to determine state, rather than using a timer to advance the state. Still, sometimes, you just need a timer…

What the blazes?

So, I’m working on an update to Loopy, which uses a shared clock object to synchronise tracks and a variety of events (like user interface updates or timed track manipulations). A tester noted that the mute/unmute quantisation feature that I’ve recently implemented, which will mute or unmute a loop at its starting point (rather than whenever you tap it), tends to overshoot a little, resulting in a small part of the beginning of the loop being audible.

Of course, there are other solutions to this particular problem (like stopping or starting playback from the audio render callback, and using Core Audio’s timestamps for exact timing), but I use timers in other places outside Core Audio’s domain, which makes Core Audio’s timing mechanism unavailable, and I wanted to see how accurate I could get the timing.

Our friend, mach_wait_until

I read in several places mention of the Mach API utility mach_wait_until (frommach/mach_time.h), which is very low-level and supposedly fairly accurate. So, based on that lead, I put together an Objective-C singleton class that launches a high-priority thread, and uses said thread to schedule events.

An NSArray of events are maintained, and a scheduleAction:target:inTimeInterval: routine creates and adds events to this array, then pokes the thread.

The thread grabs the next event in sequence, then uses mach_wait_until to sleep until the time of the next event arrives, then performs the specified action on the target. It’s kinda a DIY NSRunLoop.

Here’s a comparison between this technique, and just usingperformSelector:withObject:afterDelay: (which schedules a timer on the NSRunLoop), observed while performing various scheduled events within Loopy running on my iPhone 4 with the debugger, and derived by comparing the time of event execution with the event’s scheduled time:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer 5.5ms 0.033ms 72.0ms

That was attempt number 1: This seems to give us about 11.4ms better accuracy on average (three times more accurate).

Not bad, but it turns out mach_wait_until isn’t really that accurate, particularly if there’s a bunch of other stuff going on in other threads.

Spinning, for fun and profit

For my second attempt, the thread performs a mach_wait_until until just before the event is due, then performs a spin lock until the time arrives, using mach_absolute_time to compare the current time with the target time.

This gave further improved results — here’s that table again, but with the new scheme added, with a few different spin lock times:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer (original) 5.5ms 0.033ms 72.0ms
TPPreciseTimer (10ms spinlock) 6.0ms 0.002ms 76.5ms
TPPreciseTimer (100ms spinlock) 3.7ms 0.002ms 44.8ms
TPPreciseTimer (200ms spinlock) 2.91ms 0.002ms 74.1ms

It appears that the more stuff there is going on in other threads, the more likely themach_absolute_time call is to overshoot. So, the more time spent in the spin lock, the more leeway mach_absolute_time has to wait too long. Of course, that’s at the cost of making the CPU twiddle its thumbs for the duration.

Better than a punch in the knee

The results weren’t quite as fantastic as I’d hoped — still within the same order of magnitude, that’s for sure — but the average case for the 200ms spinlock approach is 14ms, or 5.8 times, more accurate than the traditional approach, and the minimum case is dramatically better.

You know, I think if I was aware of the results in advance, I might not bother, but I’ll stick with my hard-won 14ms now that I’m here (that’s 617 audio samples, I’ll have you know).

If anyone’s curious about the implementation (or wants to take a stab at doing better), here it is, along with a wildly simplistic commandline test app: TPPreciseTimer.zip

Now to get back to some real work.

Addendum: GCD follow-up

Chris in the comments below suggested trying a GCD-based approach, using dispatch_after. Curious, I rigged it up, and these are the stats, collected the same way as above, added to the prior table:

Mechanism Average discrepancy Minimum discrepancy Maximum discrepancy
NSRunLoop 16.9ms 0.25ms 153.7ms
TPPreciseTimer (original) 5.5ms 0.033ms 72.0ms
TPPreciseTimer (10ms spinlock) 6.0ms 0.002ms 76.5ms
TPPreciseTimer (100ms spinlock) 3.7ms 0.002ms 44.8ms
TPPreciseTimer (200ms spinlock) 2.91ms 0.002ms 74.1ms
dispatch_after (main queue) 14.8ms 0.16ms 161.2ms
dispatch_after (dedicated queue) 19.2ms 0.1ms 174.9ms
dispatch_after (dedicated queue + 100ms spinlock) 22.4ms 0.002ms 306.8ms

So, they appear pretty much the same as the NSRunLoop stats.

Reference : Here

Thanks, Keep Coding:)