Tuesday, March 12, 2013

Introduction to Core Data






Core Data: it is used to store data from your iPhone application into a Sqlite file which is present in the document directory of your application. Core Data is not a relational database, you can see Core data as a wrapper around Sqlite although core data is quite simpler as compared to Sqlite but it does not offer some of the functionality that Sqlite can offer and vice versa.



ManagedObject: Managed objects are the objects that are created by your application code to store data. A managed object can be thought of as a row or a record in a relational database table. For each new record to be added, a new managed object must be created to store the data. Similarly, retrieved data will be returned in the form of managed objects, one for each record matching the defined retrieval criteria. Managed objects are actually instances of the NSManagedObject class, or a subclass thereof. These objects are contained and maintained by the managed object context.



Persistence store coordinator: The persistent store coordinator is responsible for coordinating access to multiple persistent object stores. As an iPhone developer you will never directly interact with the persistence store coordinator and, in fact, will very rarely need to develop an application that requires more than one persistent object store. When multiple stores are required, the coordinator presents these stores to the upper layers of the Core Data stack as a single store.


Managed Object Context: Core Data based applications never interact directly with the persistent store. Instead, the application code interacts with the managed objects contained in the managed object context layer of the Core Data stack. The context maintains the status of the objects in relation to the underlying data store and manages the relationships between managed objects defined by the managed object model. All interactions with the underlying database are held temporarily in within the context until the context is instructed to save the changes, at which point the changes are passed down through the Core Data stack and written to the persistent store.

Source: http://qs4int.blogspot.in/2013/01/core-data.html
 

Thursday, March 07, 2013

Simple Example For Categories

NSDate+ComponentsExtractor.h:


 
typedef struct 
{
   NSInteger year;
   NSInteger month;
   NSInteger day;
} dateComponents;

@interface NSDate (ComponentsExtractor)
+ (dateComponents)componentsFromDate:(NSDate *)theDate;
@end
 
NSDate+ComponentsExtractor.m: 

#import "NSDate+ComponentsExtractor.h"

@implementation NSDate (ComponentsExtractor)

+ (dateComponents)componentsFromDate:(NSDate *)theDate
{
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:
                                            NSGregorianCalendar] autorelease];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | 
                                  NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags 
                                          fromDate:theDate];
    
    dateComponents theComponents;
    theComponents.year = [components year];
    theComponents.month = [components month];
    theComponents.day = [components day];
    
    return theComponents;
}

@end

Making use of the category:
NSDate *theDate = [NSDate date]; // use the current date ...
dateComponents components = [NSDate componentsFromDate:theDate];
NSLog(@"%i - %i - %i", components.year, components.month, components.day);
 
 

Friday, March 01, 2013

Shortening URLs in iOS


NSString *url = @"http://www.example.com";
NSString *apiUrl = [NSString stringWithFormat:@"http://api.tr.im/v1/trim_simple?url=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiUrl]
encoding:NSASCIIStringEncoding
error:nil];
NSLog(@"Long: %@ = Short: %@",url,shortURL);

Wednesday, February 27, 2013

Simple AsyncTask Example in Android


Any User interaction on any Android application should and must response with in 5 seconds, failure to which results in ANR Dialog. Yes "Application Not Responding" Dialog with 'Wait' and 'Force Close' inputs. Asynchronous operations can also be performed using Threads in accordance with Handler and messages to update UI about the action progress.

Here we will see how AsyncTask can be incorporated to perform Synchronous operations updated the progress of operation.

Three types are used by AsyncTask, in this case datatype is a String,

AsyncTask
First param String : This type of the parameters sent to the task upon execution.
Second param : This type of the Strings contains progress units published during the background operation.
Third param Result : This strings contains the result of the background operation.
Note : when no params are required use type void.

AsyncTask, that simplifies the creation of long-running tasks that need to communicate with the user interface.
The goal of AsyncTask is to take care of thread management.
Example :
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask {
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}

A class extend AsyncTask which triggers/perform long running tasks along side in override methods of AsyncTasks.You can specify the type, using generics, of the parameters, the progress values and the final value of the task.
  • The method doInBackground() executes automatically on a worker thread
  • onPreExecute() , onPostExecute() and onProgressUpdate() are all invoked on the UI thread
  • The value returned by doInBackground() is sent to onPostExecute()
  • You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread
  • You can cancel the task at any time, from any thread



Tuesday, February 19, 2013

Android : Stretch video to fill VideoView area


By default  Android will scale the video to fit the VideoView but keeping the video aspect ratio. That means that depending on the device's screen size there might be some black spaces left around the video the video since the it's not filling the screen.

VideoView doesn't provide an explicit way to specify the filling mode, you can achieve the same result by wrapping the video view in a Relative Layout and setting the VideoView alignments to match the parent's boundaries.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <VideoView android:id="@+id/videoViewRelative"
         android:layout_alignParentTop="true"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentRight="true"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    </VideoView>
    
</RelativeLayout>

Reverse of string in objective C


- (NSString*)reverseString:(NSString*)string
{
   NSMutableString *reversedString;
   int length     = [string length];
   reversedString = [NSMutableString stringWithCapacity:length];
   while (length--) 
   {
      [reversedString appendFormat:@"%C", [string   characterAtIndex:length]];
   }
  return reversedString;
}

Thursday, February 07, 2013

Read Missed Call in Android

private void readMissedCallAPI() {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor cursor = null;
int MISSED_CALL_TYPE = android.provider.CallLog.Calls.MISSED_TYPE;
try{
cursor = getApplicationContext().getContentResolver().query(
Uri.parse("content://call_log/calls"),
projection,
selection,
selectionArgs,
sortOrder);
while (cursor.moveToNext()) {
String callLogID = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls._ID));
String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
String callDate = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE));
String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
String callNew = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NEW));
if(Integer.parseInt(callType) == MISSED_CALL_TYPE && Integer.parseInt(callNew) > 0){
Log.v("bharath", "Missed Call Found: " + callNumber);
}
}
}catch(Exception ex){
Log.v("bharath", "ERROR: " + ex.toString());
}finally{
cursor.close();
}
}

Note:
don't forget to add android.permission.READ_CONTACTS  in Androidmainfest.xml


Create a list in SwiftUI with sticky section headers

 Sample Code import SwiftUI struct ContentView : View {     @State var isCustomViewControllerDisplayed = false     @State private va...