Saturday 15 February 2014

Simple Tricks of Obj C :

Simple Tricks of Obj C :

1. Get All HTTP Headers:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:
                                                 (NSURLResponse *)response{
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
     NSDictionary *dic = [httpResponse allHeaderFields];
}
 

2. Convert NSMutableData to NSString:

 NSString *strData = [[NSString alloc]initWithData:returnData 
                         encoding:NSUTF8StringEncoding];
 NSLog(@"strData : %@",strData);

--->  If you do this: NSLog(@"%@", returnData);
The NSData will be logged in hex format. I think that is probably what you are after.
If you want to turn it into a string and log the string, you first need to find out what character set was used. The default character set for HTTP is not UTF-8, it is ISO-8859-1. One way to do that is to examine the Content-Type header for the charset section.


NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo


4. In Objective-C, how do I test the object type?

or the line below, we have some poorly formed data that can be an NSArray, an NSDictionary or (null).

NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] 
                 objectForKey: @"Hit"];

These are the tests that were performed:

NSLog(@"%@",[hits class]);

if ([hits isMemberOfClass:[NSMutableArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isMemberOfClass:[NSMutableDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isMemberOfClass:[NSArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isMemberOfClass:[NSDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSMutableDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isKindOfClass:[NSMutableArray class]]){
    NSLog(@"%@",[hits class]);
}

5. NSString

The basic NSString class is immutable, which means its contents are set at creation and cannot later be changed. If you need to represent a different string, you must create a new string object, like this:

    NSString *name = @"John";
    name = [name stringByAppendingString:@"ny"];    // returns a new string object
 
The NSMutableString class is the mutable subclass of NSString, and allows you to 
change its character contents at runtime using methods like 
appendString: or appendFormat:, like this: 

    NSMutableString *name = [NSMutableString stringWithString:@"John"];
    [name appendString:@"ny"];   // same object, but now represents "Johnny"

 
First of all, it is very important to note, that there is a big difference between UITextView and UILabel when it comes to how text is rendered. Not only does UITextView have insets on all borders, but also the text layout inside it is slightly different.

Therefore, sizeWithFont: is a bad way to go for UITextViews.

Instead UITextView itself has a function called sizeThatFits: which will return the smallest size needed to display all contents of the UITextView inside a bounding box, that you can specify.
The following will work equally for both iOS 7 and older versions and as of right now does not include any methods, that are deprecated.

Simple Solution

- (CGFloat)textViewHeightForAttributedText: (NSAttributedString*)text 
         andWidth: (CGFloat)width {
    UITextView *calculationView = [[UITextView alloc] init];
    [calculationView setAttributedText:text];
    CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}
This function will take a NSAttributedString and the desired width as a CGFloat and
return the height needed

Check this :
http://stackoverflow.com/questions/18368567/uitableviewcell-with-uitextview-height-in-ios-7
http://stackoverflow.com/questions/19028743/ios7-uitextview-contentsize-height-alternative


7. objective - C : Loading image from URL?


- (void)loadImage:(NSURL *)imageURL{
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:imageURL];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSURL *)imageURL {
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    
    [self performSelectorOnMainThread:@selector(placeImageInUI:) 
          withObject:image waitUntilDone:YES];
}

- (void)placeImageInUI:(UIImage *)image{
    [latestIssueBtn setImage:image forState:UIControlStateNormal];
}

8.CocoaPods :

1. What is CocoaPods?
(http://guides.cocoapods.org/using/getting-started.html#installation)

CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single 
text file called a Podfile. CocoaPods will resolve dependencies between libraries, 
fetch the resulting source code, then link it together in an Xcode workspace to 
build your project.

Ultimately the goal is to improve discoverability of, 
and engagement in, third party open-source libraries by creating a more centralized 
ecosystem.

2. What is Gem ??
(http://rubydoc.info/gems/objc/0.0.3/frames)
This gem is a test suite runner for Objective-C files 
to allow for the easy execution of a test suite without the hassle 
of managing an Xcode Project File

Terminal Steps to install Pod. :

  • sudo gem update --system
  • pod install
  • touch Podfile
  • open -e Podfile
  • pod update

Refer Links :



  • Open the XIB file causing problems
  • Click on file's owner icon on the left bar (top one, looks like a yellow outlined box)
  • If you don't see the right-hand sidebar, click on the third icon above "view" in your toolbar.
    This will show the right-hand sidebar
  • In the right-hand sidebar, click on the third tab--the one that looks a bit like a newspaper
  • Under "Custom Class" at the top, make sure Class is the name of the ViewController that should
    correspond to this view. If not, enter it
  • In the right-hand sidebar, click on the last tab--the one that looks like a circle with an arrow in it
  • You should see "outlets" with "view" under it. Drag the circle next to it over to the "view" icon
    on the left bar (bottom one, looks like a white square with a thick gray outline
  • Save the xib and re-run


I can generally fix it by remaking the connection between File's Owner and the view.
Control-drag from the File's owner to your View (in IB) and select view from the pop-up menu.

10. Force a WebView link to launch Safari?


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request 
                navigationType:(UIWebViewNavigationType)navigationType; 
{
    NSURL *requestURL =[request URL]; 
    if (([[requestURL scheme ] isEqualToString: @"http"] || 
         [[requestURL scheme] isEqualToString: @"https"] || 
         [[requestURL scheme] isEqualToString: @"mailto"]) 
        && (navigationType == UIWebViewNavigationTypeLinkClicked)){ 

        return ![[UIApplication sharedApplication ] openURL:requestURL]; 
    }
    return YES; 
}

Autolayout is great. But at times you need to use a mixture of Storyboard and programmatically generated UI code. In this case Autolayout can overwrite your code settings. The trick is to use the following method:

- (void)viewDidLayoutSubviews
{

}
viewDidLayoutSubviews gets called after it processes autolayout constraints so if you need your UI code to take precedent, then you can specify things here and your code will win over autolayout.


12. Random Loream Ipsum :

- (NSString *)randomLorumIpsum {   
     NSString *lorumIpsum = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent non quam ac massa viverra semper. Maecenas mattis justo ac augue volutpat congue. Maecenas laoreet, nulla eu faucibus gravida, felis orci dictum risus, sed sodales sem eros eget risus. Morbi imperdiet sed diam et sodales. Vestibulum ut est id mauris ultrices gravida. Nulla malesuada metus ut erat malesuada, vitae ornare neque semper. Aenean a commodo justo, vel placerat odio. Curabitur vitae consequat tortor. Aenean eu magna ante. Integer tristique elit ac augue laoreet, eget pulvinar lacus dictum. Cras eleifend lacus eget pharetra elementum. Etiam fermentum eu felis eu tristique. Integer eu purus vitae turpis blandit consectetur. Nulla facilisi. Praesent bibendum massa eu metus pulvinar, quis tristique nunc commodo. Ut varius aliquam elit, a tincidunt elit aliquam non. Nunc ac leo purus. Proin condimentum placerat ligula, at tristique neque scelerisque ut. Suspendisse ut congue enim. Integer id sem nisl. Nam dignissim, lectus et dictum sollicitudin, libero augue ullamcorper justo, nec consectetur dolor arcu sed justo. Proin rutrum pharetra lectus, vel gravida ante venenatis sed. Mauris lacinia urna vehicula felis aliquet venenatis. Suspendisse non pretium sapien. Proin id dolor ultricies, dictum augue non, euismod ante. Vivamus et luctus augue, a luctus mi. Maecenas sit amet felis in magna vestibulum viverra vel ut est. Suspendisse potenti. Morbi nec odio pretium lacus laoreet volutpat sit amet at ipsum. Etiam pretium purus vitae tortor auctor, quis cursus metus vehicula. Integer ultricies facilisis arcu, non congue orci pharetra quis. Vivamus pulvinar ligula neque, et vehicula ipsum euismod quis. Aliquam ut mi elementum, malesuada velit ac, placerat leo. Donec vel neque condimentum, congue justo a, posuere tortor. Etiam mollis id ligula nec dapibus. Etiam tincidunt, nisi non cursus adipiscing, enim neque tincidunt leo, vel tincidunt quam leo non ligula. Proin a felis tellus. Pellentesque quis purus est. Nam consectetur erat quam, non ultricies tortor venenatis ac. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque at laoreet arcu. Mauris odio lorem, luctus facilisis ligula eget, malesuada pellentesque nulla.";
   
    // Split lorum ipsum words into an array
    //
    NSArray *lorumIpsumArray = [lorumIpsum componentsSeparatedByString:@" "];
   
    // Randomly choose words for variable length
    //
    int r = arc4random() % [lorumIpsumArray count];
    NSArray *lorumIpsumRandom = [lorumIpsumArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, r)]];

    // Array to string. Adding '!!!' to end of string to ensure all text is visible.
    //
    return [NSString stringWithFormat:@"%@!!!", [lorumIpsumRandom componentsJoinedByString:@" "]];

}

13.Unselect the selected row if any:

- (void)viewWillAppear:(BOOL)animated  {
    self.tableView.rowHeight = 76.0;

    // Unselect the selected row if any
    // http://forums.macrumors.com/showthread.php?t=577677
    NSIndexPath* selection = [self.tableView indexPathForSelectedRow];
    if (selection)
    {
        [self.tableView deselectRowAtIndexPath:selection animated:YES];
    }
}


14. CGRectMake and NSStringFromCGRect  :


How to NSLog the CGRect and CGFrame

CGRect rect1 = CGRectMake(100, 100, 100, 100);
CGRect rect2 = CGRectMake(190, 190, 100, 100);
 
NSLog(@"rect1: %@", NSStringFromCGRect(rect1));
NSLog(@"rect2: %@", NSStringFromCGRect(rect2));
 
CGSize size1 = CGSizeMake(100, 100);
CGSize size2 = CGSizeMake(190, 190);
 
NSLog(@"size1: %@", NSStringFromCGSize(size1));
NSLog(@"size2: %@", NSStringFromCGSize(size2))
 
 
 
 

15. Trim Audio:

-(BOOL)trimAudio {
    
    // Path of your source LOCAL audio file
    //NSString *strInputFilePath = [[[NSBundle mainBundle] resourcePath] 
                                   stringByAppendingPathComponent:@"MyAudioMemo.m4a"];
    //NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath]; 
 
 
 
    
    // Path of your source DocumentDirectory audio file    
    NSArray *pathComponents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [pathComponents objectAtIndex:0];
    NSString *strInputFilePath = [NSString stringWithFormat:@"%@%@",
                                           documentsDirectoryPath,@"/MyAudioMemo.m4a"];
                               
    NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath];

    
    // Path of your destination save audio file
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
                                                                NSUserDomainMask, YES);
    NSString *libraryCachesDirectory = [paths objectAtIndex:0];
    libraryCachesDirectory = [libraryCachesDirectory 
                                        stringByAppendingPathComponent:@"Caches"];
    
    NSString *strOutputFilePath = [NSString stringWithFormat:@"%@%@",
                                            libraryCachesDirectory,@"/abc.mp4"];

    NSURL *audioFileOutput = [NSURL fileURLWithPath:strOutputFilePath];
    
    if (!audioFileInput || !audioFileOutput)
    {
        return NO;
    }
    
    [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL];
    AVAsset *asset = [AVAsset assetWithURL:audioFileInput];
    
    AVAssetExportSession *exportSession = [AVAssetExportSession 
                                             exportSessionWithAsset:asset
                                             presetName:AVAssetExportPresetAppleM4A];
    
    if (exportSession == nil)
    {
        return NO;
    }
    
    NSLog(@"startTrimTime %f", startTrimTime);
    NSLog(@"endTrimTime %f", endTrimTime);
    
    float startTrimTime = 0;
    float endTrimTime = 5;
    
    CMTime startTime = CMTimeMake((int)(floor(startTrimTime * 100)), 100);
    CMTime stopTime = CMTimeMake((int)(ceil(endTrimTime * 100)), 100);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);
    
    exportSession.outputURL = audioFileOutput;
    exportSession.outputFileType = AVFileTypeAppleM4A;
    exportSession.timeRange = exportTimeRange;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^
     {
         if (AVAssetExportSessionStatusCompleted == exportSession.status)
         {
             NSLog(@"Success!");
             AVAudioPlayer *player = [[AVAudioPlayer alloc] 
                      initWithContentsOfURL:audioFileOutput error:nil];
             [player setDelegate:self];
             [player play];
         }
         else if (AVAssetExportSessionStatusFailed == exportSession.status)
         {
             NSLog(@"failed");
         }
     }];
    
    return YES;
} 
 
 


16.SystemConfiguration.framework appears red

 You could have deleted it from your project by accident I have done this in the past when you delete you must have move to trash instead of remove reference, I had to download xcode again to get it back.

17. Get the position of a CGPoint( which is inside a subview), W.R.T the parentView - ObjectiveC : 

UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
[self.view addSubview:subView];

CGPoint pointInSubview = CGPointMake(20, 20);
CGPoint pointInSuperview = [self.view convertPoint:pointInSubview fromView:subView];
NSLog(@"%@", NSStringFromCGPoint(pointInSuperview));
 
Prints out {70, 70} to the console


 

 

 

 

 




No comments:

Post a Comment