Wednesday, 19 October 2016

Create UIButton,UIlable and UITextfield programmatically in Swift?


UIButton:


let button = UIButton(type: .System) // let preferred over var here
        button.frame = CGRectMake(100, 100, 100, 50)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Button", forState: UIControlState.Normal)
        button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)





UILabel:



 var label: UILabel = UILabel()
    label.frame = CGRectMake(50, 50, 200, 21)
    label.backgroundColor = UIColor.blackColor()
    label.textColor = UIColor.whiteColor()
    label.textAlignment = NSTextAlignment.Center
    label.text = "test label"
    self.view.addSubview(label)


UITextField:


var txtField: UITextField = UITextField()
    txtField.frame = CGRectMake(50, 70, 200, 30)
    txtField.backgroundColor = UIColor.grayColor()
    self.view.addSubview(txtField)


Friday, 14 October 2016

Simple JSON GET Method using NSURLSession Method and NSURLSessionConfiguration (Updated).

Step 1:

In ViewController.h 

Firstly to declare the NSMutableURLRequest, NSURLSession,  NSURLSessionConfiguration, NSDictionary, NSURLSessionDataTask


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property NSMutableURLRequest *uelRequest;
@property NSURLSession *session;
@property NSURLSessionConfiguration *conifg;
@property NSDictionary *dictionaryForData;
@property NSURLSessionDataTask *dataTask;
@property (strong, nonatomic) IBOutlet UITableView *tableViewForNames;
@end


In ViewController.m 



#import "ViewController.h"

@interface ViewController () {
    NSInteger i;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    i=0;

    self.uelRequest=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://itunes.apple.com/in/rss/toppaidapplications/limit=100/json"]];
    
    self.conifg=[NSURLSessionConfiguration defaultSessionConfiguration];

    self.session=[NSURLSession sessionWithConfiguration:self.conifg];

    self.dataTask=[self.session dataTaskWithRequest:self.uelRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
    self.dictionaryForData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
     NSLog(@"%@",[[[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"]objectAtIndex:0]valueForKey:@"im:name"]valueForKey:@"label"]);
     }];

     [self.dataTask resume];
     // Do any additional setup after loading the view, typically from a nib.
}


Step3:

To Display the data in TableView.


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if (self.dictionaryForData.count>0)  {
         i=[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"] count];
    NSLog(@"%lu..........",i);
   }
   return i;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell=[[UITableViewCell alloc]init];
    cell.textLabel.text=[[[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"]objectAtIndex:indexPath.row]valueForKey:@"im:name"]valueForKey:@"label"];
    return cell;
}
@end

Multiple Selection using tableView in swift.

Step 1:

Declare Arrays.


@IBOutlet var sampleTable: UITableView!
var nameArray : NSMutableArray = NSMutableArray()
var finalArray : NSMutableArray = NSMutableArray()

Register TableViewCell in ViewDidLoad, Name is SampleTableViewCell

In ViewDidLoad to add Country names to nameArray.


 sampleTable.allowsMultipleSelection = true
 sampleTable.allowsMultipleSelectionDuringEditing = true
 sampleTable.registerNib(UINib(nibName: "SampleTableViewCell", bundle: nil), forCellReuseIdentifier: "SampleTableViewCell")





nameArray = ["India", "NZ", "England", "AUS", "PAK", "SA", "Bangladesh","Kenya","Srilanka"]

Step2:

Write TableView DataSource and Delegate Methods to Display all countries in one table.


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60
    }
    
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
    }
    
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("SampleTableViewCell", forIndexPath: indexPath) as! SampleTableViewCell
        
        cell.brandName.text = nameArray[indexPath.row] as? String
        
        if cell.selected
        {
            cell.selected = false
            if cell.accessoryType == UITableViewCellAccessoryType.None
            {
                cell.accessoryType = UITableViewCellAccessoryType.Checkmark
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryType.None
            }
        }
        
        return cell
    }
    
//didSelectRow 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        //tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        
        if cell!.selected
        {
            cell!.selected = false
            if cell!.accessoryType == UITableViewCellAccessoryType.None
            {
                cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
                finalArray.addObject((nameArray[indexPath.row] as? String)!)
            }
            else
            {
                cell!.accessoryType = UITableViewCellAccessoryType.None
                finalArray.removeObject((nameArray[indexPath.row] as? String)!)
            }
        }
        
        print(finalArray)
    }
    


In finalArray having all the selected rows.

Simple JSON Parsing POST method.

Simple JSON Using POST Method.


NSString *classIDStr = @"123";
    NSString *secIDStr = @"1";
    NSString *dairyDate = @"2016-09-15";
    
    NSString *myRequestString = [[NSString alloc] initWithFormat:@"classID=%@&sectionID=%@&dairyDate=%@", classIDStr,secIDStr,dairyDate];
    NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
    NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"Your Str"]];
    
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody: myRequestData];
    NSURLResponse *response;
    NSError *err;
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
    NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
    NSLog(@"responseData: %@", content);
    
    NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
    if ([content isEqualToString:responseString])
    {
        

    }

Simple JSON Parsing Get Method.

Simple JSON Parsing using GET Method.


NSString *requestStr = [NSString stringWithFormat:@"https://itunes.apple.com/in/rss/toppaidapplications/limit=100/json"];
    NSURL *myURL = [[NSURL alloc]initWithString:requestStr];
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
    id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
    jsonResponseDict = (NSMutableDictionary *)myJSON;
    NSMutableDictionary *dict = [jsonResponseDict valueForKey:@"feed"];

    NSLog(@"Dict %@", dict);

Thursday, 13 October 2016

Adding a View to Window in Swift

In didFinishLaunchWithOptions


window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        let mainViewController = ViewController(nibName: "ViewController", bundle: nil)
        
        window?.rootViewController = mainViewController
        window?.makeKeyAndVisible()


In Project GoTo General Deployment Info Select Main Interface to clear.

Friday, 11 March 2016

Navigate through textfields using Next/Done buttons.

In Objective-C


-(BOOL)textFieldShouldReturn:(UITextField*)textField   {
    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
    [nextResponder becomeFirstResponder];
    } else {
  
    [textField resignFirstResponder];
    }
    return NO; 

 }


In Swift


func textFieldShouldReturn(textField: UITextField!) -> Bool {   
        
        let nextTage=textField.tag+1;
        let nextResponder=textField.superview?.viewWithTag(nextTage) as UIResponder!
        
        if (nextResponder != nil){
            nextResponder?.becomeFirstResponder()
        }
        else
        {
            textField.resignFirstResponder()
        }
        return false
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        textField .resignFirstResponder()
   }