Sunday, December 9, 2012

Network Link Conditioner -- iOS

In Xode, there is a tool called "Network Link Conditioner",  it can allow the user to simulator different network connection and bandwidth. Mac and iOS developer to test their app under different network environment.


In Xcode, Xcode -> Open Developer Tool -> More Developer Tools




After enter Apple Developer Center, download the Hardware IO Tools





After install, you can see "Network Link Conditioner.prefPane"




After double click "Network Link Conditioner.prefPane",  Network Link Conditioner will added to System Preferences.




Click on "Network Link Conditioner", in Profile, it have 3G, DSL,Edge,Wifi.





You can also define your own profile, click on "Manage Profiles..."



After test, must turn off "Network Link Conditioner".

Thursday, November 1, 2012

ios 6 -- Access Address Book (Contacts)


In iOS 6, we need to get the permission to access user's contacts.(in ios 5 or below, it is no need to ask for permission).


Here is the code to access contacts works both iOS 6 and iOS 5 or below:



-(void)getAddressBookPermission
{
    
    if (ABAddressBookRequestAccessWithCompletion) { // if in iOS 6
  
    // Request authorization to Address Book
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            // First time access has been granted, add the contact
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
        // The user has previously given access, add the contact
    }
     else {
        // The user has previously denied access
        // Send an alert telling user to change privacy setting in settings app
    }
    }
    else{ // if not in iOS 6
     // just get the contacts directly
    }
}


This is the very useful tips for testing the Contacts pop up in iOS 6. 

Generally, the VERY FIRST time your app runs is the only time the ABAuthorizationStatus iskABAuthorizationStatusNotDetermined.  Then and only then will ABAddressBookRequestAccessWithCompletion() display the authorization prompt to the user.  Also, while in this state, ABAddressBookCreateWithOptions() DOES return a non-NULL ABAddressBookRef.  So there's no use in calling ABAddressBookRequestAccessWithCompletion() unless you're in this state.

If the state is kABAuthorizationStatusDenied or kABAuthorizationStatusRestricted, the only thing to do is let the user know that your app can't get access to the contacts, and if he/she WANTS your app to have access, he/she must go to Settings->Privacy->Contacts and OK the app.  (Initially, I thought I could, in this case, useABAddressBookRequestAccessWithCompletion() to ask the user for permission.  It would have been a lot more convenient for him/her.)

For testing purposes, there IS a way to get back to kABAuthorizationStatusNotDetermined.  You go to Settings->General->Reset and reset Contacts&Location.  This resets the contact and location permission settings for all apps.

Apple, if you're out there, the AddressBook docs SCREAM for more complete documentation!  This new permission stuff is quite unclear.  Even worse is any sort of docmentation about AB "sources".  A "source" is never even defined.  I figured them out but at great time-expense.  For example, nowhere is it stated that if you have multiple sources with the same contact, you'll get both contact records separately.  (One COULD assume that the system would take care of syncing contacts from multiple sources, but no.)  It's up the contact-displaying app to merge these contacts in a coherent UI.  It wouldn't so bad that this is a LOT of work if only it were documented somewhere. 

Wednesday, October 24, 2012

Performance Testing for Mobile Apps – Is Your App Ready for the Worst?

Here is artical for Mobile Apps testing

http://blog.infostretch.com/performance-testing-for-mobile-apps-a-new-game-indeed




There are some tools in the market that can help you with the performance/load, and stress testing conundrum in the mobile and web based apps space.
  1. Recent announcement by MicroFocus about SilkPerformer 9.0 (2012)  supports Mobile Web & Native apps testing on iOS, Android & BB platforms
  2. HP LoadRunner supports mobile web & native apps testing on iOS, Android, BB & WM platforms
  3. NeoLoad supports mobile web & native mobile apps
  4. JMeter supports mobile web app testing on simulators
  5. IBM Rational Performance Tester (RPT) supports mobile web app testing as well

Sunday, October 14, 2012

iOS -- CoreData data migration

Coredata provides a lightweight auto data migration method for the following conditions:

1. Simply add a new column.
2. Change a column to optional.
3. Change a optional column to compulsory, but have default value.

Step 1:
Create a new data version


1. Editor -> Add Model Version (expand your xcdatamodeld item) , type a name

2. Client on the xxxx.xcdatamodeld file and in the attribute page, set the current version



Step 2:

1. In App delegate , in method "persistentStoreCoordinator" change as follow:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"WorkXP.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

// handle db upgrade
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// Handle error


return __persistentStoreCoordinator;
}


After that, for a lightweight data migration, user don't need to remove the old version app before they install the new one.



Monday, October 1, 2012

25 iOS design resources


Here is the link for 25 iOS design resources:

http://blog.jobbole.com/26093/



Sunday, September 30, 2012

Objective C InsertionSort


-(NSMutableArray*)InsertionSort:(NSMutableArray*)array
{
    for(int j=1;j< [array count];j++)
    {
        id key = [array objectAtIndex:j];
            int i =j-1;
     
       while (i>-1 && [array objectAtIndex:i] > key) {
                [array replaceObjectAtIndex:i+1 withObject:[array objectAtIndex:i]];
                i=i-1;
            }
        [array replaceObjectAtIndex:i+1 withObject:key];
    }
    return  array;
}

Wednesday, September 5, 2012

SQL tips and articles


Recently I found 2 useful SQL functions and would like to share with you.
This function is quite useful for a DBA.
For example:
DECLARE @Object varchar(100)
SELECT @Object = 'Mem.dbo.Member'
SELECT
      PARSENAME (@Object ,3),
      PARSENAME (@Object ,2), 
      PARSENAME (@Object ,1)

You could also apply the same concept to e.g. split IP format
For example: instead of using complex charindex
DECLARE @IP char(15)

SELECT @IP = '192.168.3.11'

SELECT
      PARSENAME (@IP ,4),
      PARSENAME (@IP ,3), 
      PARSENAME (@IP ,2),
      PARSENAME (@IP ,1)   

What it does is returning the first non-null argument. It is equivalent to CASE
CASE
WHEN (expression1 IS NOT NULL) THEN expression1
WHEN (expression2 IS NOT NULL) THEN expression2
...
ELSE expression
END


Sunday, August 26, 2012

Hosting WCF in IIS

Here is the config code for web.config for hosting WCF in IIS6, windows server 2003




Key:

1. Config endpoint behaviors, using webHttp

2. binding use webHttpBinding

Wednesday, August 8, 2012

NSString Examples

NSLog


NSLog( @"The sky is %@.", @"blue" );
The preceding line of code results in this output:
The sky is blue.

Finding the Length of an NSString


NSString *string = @"A string to measure";
NSUInteger stringLength = [string length];
NSLog( @"The length is: %d.", stringLength);
results in:
The length is: 19.

Obtaining an Uppercase NSString


NSString *string1 = @"Make me taller.";
NSString *string2 = [string1 uppercaseString];
NSLog( @"Uppercased string: %@", string2 );

results in:
Uppercased string: MAKE ME TALLER.

Appending an NSString to Another NSString


NSString *string1 = @"The First Part ";
NSString *string2 = @"The Second Part";
NSString *result = [string1 stringByAppendingString: string2];
NSLog( @"Resulting string: %@", result );
results in:
Resulting string: The First Part The Second Part


Breaking a Sentence into Individual Word


NSString *string1 = @"This sentence is falling apart";
NSArray *words =
[string1 componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSLog( @"Word array: %@", words);
results in:
Word array: (
This,
sentence,
is,
falling,
apart
)

C String to NSString and Back


char* cString = "Hello Universe";
NSString* nsString = [NSString stringWithUTF8String: cString];
This code does the reverse:
NSString* nsString = @"Anybody Home?";
char* cString = [nsString UTF8String];







Monday, August 6, 2012

NSString Class Reference

Here is the link for Objective C NSString Class Reference

NSString Class Reference 

Wednesday, August 1, 2012

Sunday, July 29, 2012

iOS UI Automation Test -- Select image when using carema

When we doing a UI Automation Test in iPhone Simulation, and we would like to test the camera function.

At this point, the way is to store the image which we want to scan to iphone simulation photo library , and then pop up the image library when use camera simulation.


In the simulator, it said "Tap and hold with two fingers to select image", here is the code to do that

targt.tapWithOptions({x:0.27,y:0.45},{touchCount:2, tapCount:1,duration;1.5});


this code will pop up the photo library.




And here is the UIAElement Class Reference from Apple 


UIAElement Class Reference Link

Monday, July 23, 2012

iPhone UIAutomation Javascript -- Alert View Message

To write UIAutomation Javascript,  one hard part is to handle Alert view,

Here is the example to get Alert view's title and message:

Code:

UIATarget.onAlert = function onAlert(alert){
// To get alert title
var title = alert.name();
//To get alert body message
// [0]  is title
var message = alert.staticTexts()[1].name();

              //if(message == "Are you sure to logout?")
              if(title == "Logout")
                {
                 alert.buttons()["Yes"].tap();
                 return true;
                 }
                 return false;
              }

Thursday, July 19, 2012

iOS -- Device Capabbilities

Accessing Basic Device Information


UIDevice *device = [UIDevice currentDevice];
NSLog(@"System name: %@", device.systemName);
NSLog(@"Model: %@", device.model);
NSLog(@"Name: %@", device.name);


Working with Basic Orientation



 UIDeviceOrientationUnknown—The orientation is currently unknown.
 UIDeviceOrientationPortrait—The home button is down.
 UIDeviceOrientationPortraitUpsideDown—The home button is up.
 UIDeviceOrientationLandscapeLeft—The home button is to the right.
 UIDeviceOrientationLandscapeRight—The home button is to the left.
 UIDeviceOrientationFaceUp—The screen is face up.
 UIDeviceOrientationFaceDown—The screen is face down.

Wednesday, July 4, 2012

Automating User Interface Testing with Instruments


This is a very good article for iOS UI Automating test.

This is the link.


Another good article

This is the link

Friday, June 15, 2012

iOS -- number convert to english number

This is a app is to convert number to string, so far is up to billion. For example, 101 change to one hundred one, 11 change to eleven.

Here is the view:







Here is some explanation:

1.  Define the data

2.  Here is the recursion

     NSString *prefix = [self english_num:write];

     
 To download the code from Github, here is link:

  https://github.com/MatthewLu/numberConvert

Thursday, June 14, 2012

Javascript-- Style set Attribute not working in IE7

In some case, we want to add a style to DOM element , normally  you will do like this,




this will work in most cases, but some time when you are working for IE7 or IE6, this will not work,

so the solution as below:



Now you can add css style to Dom element in IE7 or IE6

Javascript-- Ajax cross domain for Jquery

Sometime we want to trigger a Ajax call cross other web domain,

For example, we are in www.abc.com , and you want to call a Ajax to www.123.com, you will



It will work in Firefox and Chrome, but sometimes in IE, especially for IE7 and IE6, it will not trigger this Ajax call because your call is from abc.com to 123.com.


So the solutions as fellow:





Now you can access 123.com method from abc.com.



Tuesday, June 5, 2012

Monday, June 4, 2012

iOS -- Working with Images

Reading Image Data

 1. UIImage Convenience Methods
     myImage = [UIImage imageNamed:@"icon.png"];

 2. Finding Images in the Sandbox
     NSArray *paths = [NSSearchPathForDirectoriesInDomains(
     NSDocumentDirectory, NSUserDomainMask, YES);
     return [paths lastObject];

     NSString *documentsFolder()
    {
      return [NSHomeDirectory()
      stringByAppendingPathComponent:@"Documents"];
     }

    path = [documentsFolder() stringByAppendingPathComponent:@"image.png"];
    return [UIImage imageWithContentsOfFile:path];


 3.Loading Images from URLs
    NSURL *url = [NSURL URLWithString:
    @"http://image.weather.com/images/maps/current/curwx_600x405.jpg"];

    UIImage *img = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:url]];


    load itself asynchronously without blocking the main thread


   // Create an asynchronous background queue

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:
    ^{
      // Load the weather data

      NSURL *weatherURL = [NSURL URLWithString:@"http://image.weather.com/images\
      /maps/current/curwx_600x405.jpg"];

      NSData *imageData = [NSData dataWithContentsOfURL:weatherURL];

     // Update the image on the main thread using the main queue

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

    UIImage *weatherImage = [UIImage imageWithData:imageData];

    imageView.image = weatherImage;}];

Thursday, May 31, 2012

iOS-- Managing Subviews


1. Adding Subviews

  •  insertSubview:atIndex:
  •  insertSubview:aboveSubview:
  •  insertSubview:belowSubview:



2. Reordering and Removing Subviews

  • Use [parentView exchangeSubviewAtIndex:i withSubviewAtIndex:j] to exchange the positions of two views.
  • Move subviews to the front or back using bringSubviewToFront: and 
  • sendSubviewToBack.
  • To remove a subview from its parent, call [childView removeFromSuperview]. If 
  • the child view had been onscreen, it disappears. Removing a child from the superview 
  • calls a release on the subview, allowing its memory to be freed if its retain
  • count has returned to 0.

3. View Callback

  •  didAddSubview: is sent to a view after a successful invocation of addSubview: lets subclasses of UIView perform additional actions when new views are added.
  • didMoveToSuperview: informs views that they’ve been re-parented to a new superview. The view may want to respond to that new parent in some way.When the view was removed from its superview, the new parent is nil.
  • willMoveToSuperview: is sent before the move occurs.
  • didMoveToWindow: provides the callback equivalent of didMoveToSuperview but when the view moves to a new Window hierarchy instead of to just a new superview.
  • willMoveToWindow: is, again, sent before the move occurs.
  • willRemoveSubview: informs the parent view that the child view is about to be removed.

Wednesday, May 30, 2012

iOS-- URL encode


1. First method




2.Second method




Tuesday, May 29, 2012

iOS-- Convert string to date


To convert a string to date format
if the string format is like "22/05/2012 9:58:33 AM"

code:





Monday, May 28, 2012

iOS - Performing Runtime Compatibility Checks


  • Check platform geometry   
      if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)




  • Check deployment platform  
      if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) 




  •   Check system prefix       
       if ([[[UIDevice currentDevice] systemVersion] hasPrefix:@"5."])    




  •  Check for properties using key-value coding    
       UILabel *label = (UILabel *)[cell valueForKey:@"textLabel"];
       if (label) [label setText:celltext]; 



  •   Check for class existence    
               if (NSClassFromString(@"NSAttributedString")) . . .



  •  Check for function existence       
       if(&UIGraphicsBeginImageContextWithOptions != NULL) . . .



  •   Check for selector compliance    
        if ([cell respondsToSelector:@selector(selectorName:)])    

Sunday, May 27, 2012

IOS -- INTRODUCING BLOCK



1. What is block


     A block is an anonymous inline collection of code that:
  • Has a typed argument list just like a function
  • Has an inferred or declared return type
  • Can capture state from the lexical scope within which it is defined
  • Can optionally modify the state of the lexical scope
  • Can share the potential for modification with other blocks defined within the same lexical scope
  • Can continue to share and modify state defined within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed

2. Declare and using block








image: ../Art/blocks.jpg








3. __block modifier


   __block variables live in storage that is shared between the lexical scope of the variable and all blocks and   block copies declared or created within the variable’s lexical scope. 





Thursday, May 24, 2012

Change iOS app specific store in iTunes Connect

To change where your app will be sold.

1. Go to Rights and Price


2. Select "Specific Stores"



3. Choose the country you want your app sell and save


Thursday, May 3, 2012

SQL tip


Nice article. simple and easy to understand

RAID and Its impact on your SQL performance


Saturday, April 21, 2012

How to use Git for Visual Studio 2010

                                            Use Git in Visual Studio 2010

    1) Install Git
         http://www.git-scm.com/download

    2) Install Git Extension
        http://code.google.com/p/gitextensions/downloads/list 
      Choose GitExtensionxxxSetupComplete.msi,
      must choose msysGit and KDiff3


    3)Install Git Source Control Provider
      
       Open VS 2010, Select Tool, then select
       Search Git and download Git Source Control Provider
     
    After install, restart VS2010,  select "Tool", then select "Option", Then open "Source Control", select "Git Source Control Provider", then "OK"
   
   

    Now you can use Git as source control. And create a account in GitHub , then push your code to it.
 

Wednesday, April 18, 2012

Xcode 4.2 support iOS 5.1


Xcode 4.2 only support up to iOS 5.0 ,but the following method can allow you to run iOS5.1 in Xcode 4.2.

Download Xcode 4.3.1 dmg first, and then :
1. Copy folder

    copy /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/5.1 (9B176) to
   Developer/Platformes/iPhoneOS.platform/DeviceSupport

   command:

   sudo cp -Rpvn "/Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/5.1 (9B176) " 
/Developer/Platforms/iPhoneOS.platform/


2. Copy folder

    copy  /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk to
    Developer/Platformes/iPhoneOS.platform/Developer/SDKs

    command:

      sudo cp -Rpvn " /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk " 
/Developer/Platforms/iPhoneOS.platform/

3. Copy folder

     copy /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk to
     Developer/Platformes/iPhoneOS.platform/Developer/SDKs

  Command:


sudo cp -Rpvn " /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs /iPhoneOS5.1.sdk " 
/Developer/Platforms/iPhoneOS.platform/

4.  Copy version.plist

     sudo cp -n  /Volumes/Xcode/Xcode.app//Contents/Developer/Platforms/iPhoneOS.platform/version.plist /Developer/platform/version.plist /Developer/Platforms/iPhoneOS.platform/version.plist

5. restart Xcode

Now it will support iOS5.1 debug in Xcode 4.2

Tuesday, April 17, 2012

Tip - SQL cheat sheet


iOS-Passing Data between View Controller


Method one:
Open the project we just created in last post.

Step 1:
Select the AppDelegate.h file, add your variable 

Step 2:
Synthesize the object in AppDelegate.m file and initialize it when the application becomes active:



Step 3
Set value to the variable, in ViewController.m file, in secondPageBtnPress method, import “AppDelegate.h”.




Step 4
Get the value in the second page, in “SecondPage_ViewController.h”, define a IBoutlet for the label.
       



  Then connect the label to IBOutlet, click “SecondPage_ViewController.xib”,          Right click the “File owner” icon, drag and drop to the “Second Page” label, select the “label” in the popup.





Step 5
       Get the value and set to the “Second Page” label
In “SecondPage_ViewController.m”, import “AppDelegate.h”, synthesize the label, and in the viewDidLoad method to get the value.



Step 6
Run the app, and it will show like this:






Thursday, April 12, 2012

Page navigation in ios app

Use storyboard



Notes: storyboard is the new feature, is not supported by IOS 4 SDK, so if want to build an app which support IOS 4, please use xib.

Step 1:
Create a Single View Application Project; Make sure “Use Storyboard” is clicked.



 Step 2:
Click on the “storyboard” file, and click “Editor” and click “Embed In” and click “Navigation Controller”



Add a label on the view, and change the label to “Page 1”, and then add a button to “Page 1”, name to button to “Page 2”

Then the storyboard will show like this,



Step 3:
Drag and drop a new View Controller in the storyboard, and add a label on it, change the label to “Page 2”



Step 4
Right click the “Page 2” button on the “Page 1” view controller and drag the mouse point to “Page 2” view controller, select “Push” when the “Storyboard Segues” popup.



Then the storyboard will shown like this:


Step 5
Run the app, and press the “Page 2” button, the app will navigate the page from “Page 1” to “Page 2”

For more detail about page navigation and tab bar:



Use xib 
Step 1
               Create a single view application project; make sure the “Use Storyboard” unclicked. 


          Step 2
         We need to add the navigation controller to the first view.  Click on the “AppDelegate.m”, under the               “didFinishLaunchingWithOptions” function, you will see the code below:
This code is to find the “ViewController” page, and add this page as the first page. 

We start to add a “Navigation Controller” to the view.

In AppDelegate.h,
 We define a “navigationController”, the code as below:
Step 3

 Click on the ViewController.xib , drag and drop a label on it and change the label to “First Page”, drag and drop a button on it and change the text to “Second Page”.

Step 5
Click the “ViewController.h”, we need to add an IBOutlet to connect to button we just created in the view.



Step 6
Click the “ViewController.xib”, right click on the “File own” icon, and drag to the “Second Page” button, select the “secondPageBtn” from the popup. 

Step 7
Now we create the second page, click on “New File”.


Select “Cocoa Touch” and select “UIViewController Subclass”


Name the class “SecondPage_ViewController”

Step 8
Click on the “SecondPage_ViewController.xib”, drag and drop a label on it, and change the label to “Second Page”

Step 9
Click on the “ViewController.m”, first, import the “SecondPage_ViewController.h”, second, and synthesize the “secondPageBtn” we define in “ViewController.h”. Last, we create a method to handle the press action by the button; we name the method to “secondPageBtnPress”.


Step 10
Now we need to connect the press action to the “secondPageBtnPress” method.

Click on the “ViewController.xib”, right click the “Second Page” button, drag to the first responder icon , select “secondPageBtnPress” on the popup



Make sure the “Touch Up Inside” connect to the “secondPageBtnPress” method 

Step 11
Run the app, and press the button, it will navigate to the second page.