Connect mobiles service with windows azure for insert/delete/update data schemaAppmobileData [iOS]


Manage Service Azure
1. Create mobileService in Windows Azure
2. Create database in mobile service name 'myTable'


download iOS SDK และ Connect app in quickstart windowsAzure

  • Connect your app
    In your Xcode project, add the Mobile Services libraries to your project. Drag the WindowsAzureMobileServices.framework folder from the Finder into your project, as shown below.
    Add the import to your AppDelegate.h file:
    #import <WindowsAzureMobileServices/WindowsAzureMobileServices.h>
    Add the following public property
    @property (strong, nonatomic) MSClient *client;
    Add the following code to your AppDelegate.m file in the application:didFinishLaunchingWithOptions operation:
    self.client = [MSClient clientWithApplicationURLString:@"https://[URL MobileService Create].azure-mobile.net/" applicationKey:@"XXXXXXXXXXXXXXXXXX"];

3. Add SDK Azure to project

4. coding
in Xcode new file objective-c name MyTableModel for example without interface
Xcode create file MyTableModel.h and MyTableModel.m

code for MyTableModel.h >>>>
#import <Foundation/Foundation.h>
#import <WindowsAzureMobileServices/WindowsAzureMobileServices.h>
#import "AppDelegate.h"


typedef void (^QSCompletionBlock) ();
typedef void (^QSCompletionWithIndexBlock) (NSString *index);
typedef void (^QSBusyUpdateBlock) (BOOL busy);

@interface MyTableModel : NSObject

@property (nonatomic, strong) NSArray *items;
@property (nonatomic, strong) MSClient *client;
@property (nonatomic, copy) QSBusyUpdateBlock busyUpdate;

+ (MyTableModel *)defaultService;

- (void)addItem:(NSDictionary *)item completion:(QSCompletionWithIndexBlock)completion; 

- (void)refreshDataOnSuccess:(QSCompletionBlock)completion; 
- (void)refreshDataOnSuccessWhile:(NSInteger)cunt completion:(QSCompletionBlock)completion; //Select where

- (void)updateItem:(NSDictionary *)item completion:(QSCompletionBlock)completion; 
- (void)deleteItem:(NSDictionary *)item completion:(QSCompletionBlock)completion;

- (void)handleRequest:(NSURLRequest *)request next:(MSFilterNextBlock)next response:(MSFilterResponseBlock)response;

- (void)registerDeviceToken:(NSString *)deviceToken;
@end


code for MyTableModel.m >>>>
#import "MyTableModel.h"
#import <WindowsAzureMobileServices/WindowsAzureMobileServices.h>

@interface MyTableModel() <MSFilter>

@property (nonatomic, strong) MSTable *table;
@property (nonatomic) NSInteger busyCount;

@end

@implementation MyTableModel

@synthesize items;


+ (MyTableModel *)defaultService
{
    // Create a singleton instance of MyMemberService
    static MyTableModel* service;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [[MyTableModel alloc] init];
    });
    return service;
}

#pragma - Connection Azure mobile service
-(MyTableModel  *)init
{
    self = [super init];
    if (self)
    {
        MSClient *client = [MSClient clientWithApplicationURLString:@"https://[URL MobileService Create].azure-mobile.net/" applicationKey:@"XXXXXXXXXXXXXXX"];
        self.client = [client clientWithFilter:self];
        
        self.table = [_client tableWithName:@"myTable"];
        
        self.items = [[NSMutableArray alloc] init];
        self.busyCount = 0;
    }
    return self;
}

#pragma - Action insert/delete/update
-(void)addItem:(NSDictionary *)item completion:(QSCompletionWithIndexBlock)completion
{
    [self.table insert:item completion:^(NSDictionary *result, NSError *error)
     {
         [self logErrorIfNotNil:error];
         
         NSUInteger index = [items count];
         [(NSMutableArray *)items insertObject:result atIndex:index];
         
         completion([NSString stringWithFormat:@"%@",error]);
     }];
}

// Select All
- (void)refreshDataOnSuccess:(QSCompletionBlock)completion
{
    [self.table readWithCompletion:^(NSArray *results, NSInteger totalCount, NSError *error) {
        [self logErrorIfNotNil:error];
        items = [results mutableCopy];
        completion();
    }];
}

// Select Condition
- (void)refreshDataOnSuccessWhile:(NSInteger)cunt completion:(QSCompletionBlock)completion
{
    NSString *selectWhile = [NSString stringWithFormat:@"idUser == %d",cunt];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:selectWhile];
    [self.table readWithPredicate:predicate completion:^(NSArray *result, NSInteger totalCount, NSError *error) {
        [self logErrorIfNotNil:error];
        
        items = [result mutableCopy];
        
        completion();
    }];
}

-(void)updateItem:(NSDictionary *)mutable completion:(QSCompletionBlock)completion
{
    [self.table update:mutable completion:^(NSDictionary *item, NSError *error) {
        [self logErrorIfNotNil:error];
        completion();
    }];
}

-(void)deleteItem:(NSDictionary *)item completion:(QSCompletionBlock)completion
{
    [self.table delete:item completion:^(NSNumber *itemId, NSError *error)
    {
        [self logErrorIfNotNil:error];
        completion();
    }];
}

- (void)busy:(BOOL)busy
{
    if (busy)
    {
        if (self.busyCount == 0 && self.busyUpdate != nil)
        {
            self.busyUpdate(YES);
        }
        self.busyCount ++;
    }
    else
    {
        if (self.busyCount == 1 && self.busyUpdate != nil)
        {
            self.busyUpdate(FALSE);
        }
        self.busyCount--;
    }
}

#pragma - Error
- (void)logErrorIfNotNil:(NSError *) error
{
    if (error)
    {
        NSLog(@"ERROR %@", error);
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Server ServiceProblem.!"
                                                          message:@"A server with the specified hostname could not be found."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
    }
}

- (void)handleRequest:(NSURLRequest *)request
                 next:(MSFilterNextBlock)next
             response:(MSFilterResponseBlock)response
{
    MSFilterResponseBlock wrappedResponse = ^(NSHTTPURLResponse *innerResponse, NSData *data, NSError *error)
    {
        [self busy:NO];
        response(innerResponse, data, error);
    };
    [self busy:YES];
    next(request, wrappedResponse);
}

@end

5. new file interface create name MobileServiceViewController for example
add button insert and delete
-(IBAction)dataInsertService:(id)sender;
-(IBAction)dataSelectService:(id)sender;

- in MobileServiceViewController.h following code
#import <UIKit/UIKit.h>
#import <WindowsAzureMobileServices/WindowsAzureMobileServices.h>
#import "MyTableModel.h"

@interface MobileServiceViewController : UIViewController 

@property (nonatomic, strong) IBOutlet UIButton *btnInsert;
@property (nonatomic, strong) IBOutlet UIButton *btnSelect;
@property (nonatomicstrongIBOutlet UIButton *btnUpdate;
@property (nonatomicstrongIBOutlet UIButton *btnDelete;

-(IBAction)dataInsertService:(id)sender;
-(IBAction)dataSelectService:(id)sender;
-(IBAction)onUpdate:(id)sender;
-(IBAction)onDelete:(id)sender;

@end


- in MobileServiceViewController.m following code method insert and select
- (void)viewDidLoad
{
    [super viewDidLoad];
    TableModel = [MyTableModel defaultService];
    self.TableModel.busyUpdate = ^(BOOL busy)
    {
        if (busy) {
            NSLog(@"Loading");
        } else {
            NSLog(@"Complete");;
        }
    };
}

-(IBAction)dataInsertService:(id)sender
{
    NSDictionary *item = @{@"Field1" : @"Data1", @"Field2" : @"Data2", @"Field3" : @"Data3", @"Field4" : @"Data4",......};
    [self.TableModel addItem:item completion:^(NSString *index)
     {
         NSLog(@"Insert");
     }];
}

- (IBAction)dataSelectService:(id)sender
{
    TableModel = [MyTableModel defaultService];
    if ([Parameter search].length == 0) { // Select *
        NSLog(@"dataSelect *");
        [TableModel refreshDataOnSuccess:^{
            NSLog(@"Successfully Selection Data");
        }];
    } else { //Condition select
        NSLog(@"dataSelect Condition");
        [TableModel refreshDataOnSuccessWhile:[Parameter search] completion:^{
            NSLog([NSString stringWithFormat:@"%@ : %@", @"Successfully Selection Data Condition"[Parameter search]]);
        }];
    }
}

- (IBAction)onUpdate:(id)sender
{
    NSLog(@"onUpdate");
    NSDictionary *itemUpdate = [[NSDictionary alloc] init];
    itemUpdate = @{@"Field1" : @"Data1", @"Field2" : @"Data2", @"Field3" : @"Data3", @"Field4"@"Data4",......};
    [TableModel updateItem:itemUpdate completion:^(NSUInteger index)
    {
          NSLog(@"Update");
    }];
}
[Parameter search] is data anything from textfield, string, int, float, double, etc for selected

-(IBAction)onDelete:(id)sender
{
        NSDictionary *item = [self.TableModel.items objectAtIndex:[1,2,3,4,.. in Array]];
        [self.TableModel deleteItem:item completion:^
        {
            NSLog(@"Delete");
        }];
}


---------------------------------------------------------------------------------------------------------------------
UITableView EditDelete Interface

@interface MobileServiceViewController ()
@property (nonatomic, strong) MyTableModel *TableModel;


@end
@implementation MobileServiceViewController
{
    BOOL boolDelete;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.itemEdit = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:nil target:self action:@selector(CategoriesMenu)];
    self.navigationItem.rightBarButtonItem = self.itemEdit;
        
    TableModel = [MyTableModel defaultService];
    self.TableModel.busyUpdate = ^(BOOL busy)
    {
        if (busy) {
            NSLog(@"Loading");
        } else {
            NSLog(@"Complete");;
        }
    };

}

- (void)CategoriesMenu
{
    NSLog(@"CategoriesMenu");
    if(!boolDelete)
    {
        boolDelete = TRUE;
        [myTableView setEditing:YES animated:YES];
        [self.itemEdit setTitle:@"Cancel"];
    } else {
        boolDelete = FALSE;
        [myTableView setEditing:NO animated:YES];
        [self.itemEdit setTitle:@"Edit"];
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if ([TableModel.items count] <= 0) {
        NSLog(@"Error");
    }
    else {
        NSDictionary *tmpDict = [TableModel.items objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@",[tmpDict objectForKey:@"Field1"]];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [TableModel.items count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     //Code selected action > indexPath.row
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *item = [self.TableModel.items objectAtIndex:indexPath.row];
        [self.TableModel deleteItem:item completion:^
        {
            [SVProgressHUD showWithStatus:@"Delete Data Successfully"];
            if(boolDelete)
            {
                boolDelete = FALSE;
                [myTableView setEditing:NO animated:YES];
                [itemEdit setTitle:@"Edit"];
            }
            [self refresh];
        }];
    }
}

- (void) refresh
{
    self.TableModel = [MyTableModel defaultService];
    [self.TableModel refreshDataOnSuccess:^
    {
        [myTableView reloadData];
    }];

}


finally in MobileServiceViewController.h
add code this
@interface MobileServiceViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>


Comments

Popular posts from this blog

รู้จักกับ Breakpoints ใน Responsive Web Design

IS-IS & OSPF

RIP Routing Information Protocol