Latest Post

Tuesday, 10 March 2015

Jogendra Singh

SOAP webservice calling in iOS with xml parsing

       
Here we are learning , How to call SOAP webservice in iOS with XML parsing " -

In this tutorial , we will use a third party class for XML parsing that is "XMLReader" 
         NSString *soapMessage = [NSString stringWithFormat:
                             @"\n"
                             "\n"
                             "\n"
                             "<newslist xmlns=\"http://tempuri.org/\">\n"
                             "%@\n"  "</newslist>\n"  "
\n"   "\n",[userDefaults valueForKey:@"languageId" ];  // This XML is not showing proper here show visit on  XML String Type   
Here XML is not showing properly show visit on this url XML String Type

      //newslist = It my webservice name that I am going to call and this XML is showing in your browser if you will call your webservice URL
//pi  = Its variable , In this I am sending data on server of my language id

 NSString *soapAction = [NSString stringWithFormat:@"http://tempuri.org/%@",@"newslist"]; // Here your webservice name that you wants to call 
        NSURL *url = [NSURL URLWithString: @"Enter Here your webservice url" ];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            [request setHTTPMethod:@"POST"];
            NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];
            [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            [request addValue: soapAction forHTTPHeaderField:@"SOAPAction"];
            [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

            NSURLResponse* response;
            NSError* error;
            NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            NSString *  rsltStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
          
            NSError *parseError = nil;
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:rsltStr error:&parseError];  // In this I have used XMLReader file

        //you can download XMLReader file her using this like XMLReader FILE DOWNLOAD 

Here in xmlDictionary you will get result from server with xml parsed.


Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 


Read More

Wednesday, 28 January 2015

Jogendra Singh

Currency format in output in swift language


I'm looking for a way to format a string into currency using the UITextField  in language swift for iOS 8
Using NSNumberFormatter to format currency in output swift language


For example, i'd like to have the number "123456" converted into "$1,234.45" Or if I have a number under 1$, I would like it to look like this: "12" -> "$0.12"

I use this code. This work for me
1)  Add UITextField Delegate to header file
2) Add this code  


  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        if textField.tag == 100 && phoneNumberValidation(string) || string == "" && phoneNumberValidation(string)
        {
            var cleanArray = textField.text.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) as NSArray
            var cleanCentString  = cleanArray.componentsJoinedByString("")
            var centAmount:NSInteger! =  cleanCentString.toInt()
            if countElements(string) > 0
            {
                if centAmount == nil
                {
                    centAmount = 0
                }
                centAmount = centAmount * 10 + string.toInt()!
            }else
            {
                centAmount = centAmount / 10
            }
            var floatValue = Double(centAmount) / 100
            var amount = NSNumber(double:  floatValue )
            var _currencyFormatter = NSNumberFormatter()
            _currencyFormatter.numberStyle = .CurrencyStyle
            _currencyFormatter.currencyCode = "USD"
            _currencyFormatter.negativeFormat = "-¤#,##0.00"
            textField.text = _currencyFormatter.stringFromNumber(amount)
        }
        if textField.tag != 100 {
            return true
        }
        return false
    }
    
    
    
    func phoneNumberValidation(value: String) -> Bool {
        var charcter  = NSCharacterSet(charactersInString: "0123456789").invertedSet
        var filtered:NSString!
        var inputString:NSArray = value.componentsSeparatedByCharactersInSet(charcter)
        filtered = inputString.componentsJoinedByString("")
        return  value == filtered
    }

Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 
Read More

Thursday, 22 January 2015

Jogendra Singh

In iOS form Phone number validation in swift language


Simple phone number validation in swift ios 8 , Using this function  you can easily  check phone number . Also have some example for this using NSPredicate etc

you can see lots of method for number validation. But I made this sort method


    func phoneNumberValidation(value: String) -> Bool {
        var charcter  = NSCharacterSet(charactersInString: "0123456789").invertedSet
        var filtered:NSString!
        var inputString:NSArray = value.componentsSeparatedByCharactersInSet(charcter)
        filtered = inputString.componentsJoinedByString("")
        return  value == filtered
    }

How to use this validation function in code

if    self.phoneNumberValidation(contactNumTextF.text) == false  {
            let alert = UIAlertView()
            alert.title = "Message"
            alert.message = "Enter Valid Contact Number"
            alert.addButtonWithTitle("Ok")
            alert.delegate = self
            alert.show() 
}else {
            // Number valid
         } 


You can also check this validation in Objective C Language  simple phone number validation in IPhone sdk Objective C

Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 
Read More

Friday, 9 January 2015

Jogendra Singh

UITextField move up when keyboard appears in Swift

UITextField move up when keyboard appears in Swift   :  In swift language have minor change other thing have same - 

Moving view on click of UITexField in swift language

Some textfield hide behind keyboard so how can we move view on textfield editing . So we can work on this ..

Here I have make a function for this , in this you can pass want view move then pass "true" and with your movement height



    func textFieldDidBeginEditing(textField: UITextField) {
            animateViewMoving(true, moveValue: 100)
    }
    func textFieldDidEndEditing(textField: UITextField) {
            animateViewMoving(false, moveValue: 100)
    }
    
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        var movementDuration:NSTimeInterval = 0.3
        var movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration )
        self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
        UIView.commitAnimations()
    }

If you want do this same thing in objective-C then visit on this post Moving UIView up when UITextField is selected

Try this it will work fine , I have tested this ..




Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 
Read More

Saturday, 6 December 2014

Jogendra Singh

UITableview with UISearchBar in swift Language

Create UISearchBar with UITableView in swift language ( iOS8 ). 


In this tutorials we are going to learn how to work UISearchBar with UITableView in swift language .
        UISearchBar Class implements a simple a text field for searches . UISearchBar object does not perform direct we need to user UISearchBarDelegate for this and implement the action when text entered and button clicked.



First Need to create UITableView in swift  : -  How to create / make a simple tableview in iOS8 and swift

Now need to implement UISearchBar in this

   Create global objects  : -

    @IBOutlet var tableView:UITableView!   // This is for your tableview
    
    @IBOutlet var searchBarObj:UISearchBar!  // It's for your search bar object 
    
    var is_searching:Bool!   // It's flag for searching  
    var dataArray:NSMutableArray!  // Its data array for UITableview 
    var searchingDataArray:NSMutableArray! // Its data searching array that need for search result show 


Add Delegate of UITableView and UISearchbar

class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate


Now initialise all array and search flag

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        is_searching = false
        dataArray = ["Apple", "Samsung", "iPHone", "iPad", "Macbook", "iMac" , "Mac Mini"]
        searchingDataArray = []
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
    }

Now we need to minor change in UITableViewDataSource functions


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if is_searching == true{
            return searchingDataArray.count
        }else{
            return dataArray.count  //Currently Giving default Value
        }
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        if is_searching == true{
            cell.textLabel.text = searchingDataArray[indexPath.row] as NSString
        }else{
            cell.textLabel.text = dataArray[indexPath.row] as NSString
        }
        return cell;
    }

Hows show in simulator now : -





Now need to implement UISearchBar Delegate function


    func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
        if searchBar.text.isEmpty{
            is_searching = false
            tableView.reloadData()
        } else {
            println(" search text %@ ",searchBar.text as NSString)
            is_searching = true
            searchingDataArray.removeAllObjects()
            for var index = 0; index < dataArray.count; index++
            {
                var currentString = dataArray.objectAtIndex(index) as String
                if currentString.lowercaseString.rangeOfString(searchText.lowercaseString)  != nil {
                    searchingDataArray.addObject(currentString)
                    
                }
            }
            tableView.reloadData()
        }
      } 

After searching we can result showing according to our search 





Using this delegate function we can search text using UISearchBar   in UITableView

Download Sample Project from here : - UITableView with SearchBar xCode Project


Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 
Read More

Monday, 24 November 2014

Jogendra Singh

UISwitch example in swift ios8


How to make UISwitch button in swift language ?


   UISwitch button is return a boolean value like : - true , false , yes , no etc.  In this tutorial we're going to learn example of UISwitch button in swift language, 


Open Object and create new project for UISwitch button .  name of project is "UISwitchExampleSwift" and select language is SWIFT.




Now go in Main.storyboard and drag and drop UISwitch button and One UILabel for showing current state of UISwitch button . 



Now Make object of both UISwitch button and UILabel or also make action of UISwitch Like this :- 

    @IBOutlet
           var switchBtnObj : UISwitch!

    @IBOutlet
 var stateLabelObj : UILabel

and Action of UISwitch button :-

 @IBAction func switchBtnClicked   (switchBtn : UISwitch ){
            } 


Connect both of in Storyboard like this :-



Now need to check in Action using if condition like this :- 

    @IBAction func switchBtnClicked   (switchBtn : UISwitch ){
        if switchBtn.on{
            stateLabelObj.text = "Switch btn is on now"
        }else{
            stateLabelObj.text = "Switch btn is off now"
        }
    }

And change in display :-   If button is off 


Check if Button is On




Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 







Read More

Saturday, 22 November 2014

Jogendra Singh

Image Resize in swift ios8

How  to resize an image?

In this tutorials We are going to learn "How can resize UIImage in swift language".  Without resize image we can get full image in our view  

First I am showing image that in original size 



If we check this image size than we see image size is "1366 × 768" .
We're not able to show full image in our iPhone screen.

Now Need to check How looks this iPhone without resize 

Setting image in backgroud of UIView


        self.view.backgroundColor = UIColor(patternImage:UIImage(named: "bg Image.jpg")!)

After doing this setup, we see in simulator this type .


In this image we can see image's only few part is showing., so we need to resize image 


Resizing UIImage in swift 

I have made function that can we use for resize image, In that we need to pass original image and size that we need . 

    func imageResize (imageObj:UIImage, sizeChange:CGSize)-> UIImage{
        
         let hasAlpha = false
        let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
        
        UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
        imageObj.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
        
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        return scaledImage
    }


How to call this function  : - 


               var mainScreenSize : CGSize = UIScreen.mainScreen().bounds.size // Getting main screen size of iPhone
        
             var imageObbj:UIImage! =   self.imageResize(UIImage(named: "bg Image.jpg")!, sizeChange: CGSizeMake(mainScreenSize.width, mainScreenSize.height))
        
   self.view.backgroundColor = UIColor(patternImage:imageObbj) 



After doing this setup we see again image in device that looks like this :-





   We can see in this image is fit in screen .





Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 



Read More

Friday, 21 November 2014

Jogendra Singh

UIPickerView make in Swift iOS


How to make or create UIPickerView in swift language


What is pickerview : - UIPickerView use for user select value by rotating the wheel for his desired value.  In pickerview have rows and component for user interface .  


Going to learn UIPickerView : -  

                  Open xCode and create new project UIPickerViewSwift  and select Swift language .


Now go in ViewController.swift and create Object of picker view 

    @IBOutlet
    var pickerViewObj : UIPickerView!

  Now go in storyboard and drag and drop UIPickerView and connect to object like this :- 






also connect delegate and datasource  

adding datasource and delegate in ViewController.swift

class ViewController: UIViewController ,UIPickerViewDataSource, UIPickerViewDelegate  {
          }



Create content array that you want to show on PickerView

    var pickerValueArray = ["Welcome", "on", "our", "site", "jogendra.com"]

Add datasource and delegate function of pickerview

  func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 1;
    }
    
    // returns the # of rows in each component..
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return pickerValueArray.count;
    }

//Title showing
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
    {
        return pickerValueArray[row]
    }

  For Selection value add this 
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        NSLog("Value Printing %@",pickerValueArray[row]);
        
     }






Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 






Read More

Monday, 17 November 2014

Jogendra Singh

How to make UIDatePicker in iOS with Swift


Here we are going to learn UIDatePicker in swift :-


       The Date Picker in iOS 8 provides an custom Picker View that uses multiple rotating wheels to allow users to select dates and times. In this tutorial the current selected date is presented onscreen inside a label. This tutorial is written in Swift so you will need Xcode 6. It can be downloaded at Apple's developer portal.



        Open Xcode and create a new Single View Application. For product name, use UIDatePickerSwift  and then fill out the Organization Name (ex. jogendra) and Organization Identifier (Ex. com.jogendra.datePicker) with your customary values. Enter Swift as Language and make sure only iPhone/iPad/Universal is selected in Devices.



      Drag a UILabel or  UITextField (According to your requirement ) to the View Controller change the UILabel or  UITextField text to "Select Date". Next, drag a Date Picker to the View Controller and center it. The Storyboard should look like this.



Create object of both UIDatePickerView and UITextField :- 

class ViewController: UIViewController {

    @IBOutlet
    var textField:UITextField!
    
    @IBOutlet
    var datePickerObj:UIDatePicker
        }


And Make action of UIDatePickerView
      @IBAction  func datePickerClicked( datePicker:UIDatePicker){
                 }

Connect in Storyboard




After doing these steps  do work in function of datepicker for change value 

    @IBAction  func datePickerClicked( datePicker:UIDatePicker){
        
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
        var dateStr = dateFormatter.stringFromDate(datePicker.date)
        textField.text = dateStr
        
    }

It's look like this :-
Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 









Read More

Tuesday, 11 November 2014

Jogendra Singh

In iOS UIWebView create / make in Swift / iOS Sdk



How to create UIWebview programmatically create in swift and iOS 8 .


In this tutorial going to learn about UIWebview :-   

Some times we need to open some url or load some html content in our application

Creating UIWebview 
override func viewDidLoad() {
    super.viewDidLoad()
    let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.jogendra.com")))
    webV.delegate = self;
    self.view.addSubview(webV)
}

How to use UIWebview delegate in swift language

First need to you take delegate in your header file

class myViewController: UIViewController, UIWebViewDelegate 

Now need to add delegate functions on UIWebview .. 


func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
    print("Webview fail with error \(error)");
}

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -&gt; Bool {
    return true;
}

func webViewDidStartLoad(webView: UIWebView!) {
    print("Webview started Loading")
}

func webViewDidFinishLoad(webView: UIWebView!) {
    print("Webview did finish load")
}


Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+
Read More

Friday, 17 October 2014

Jogendra Singh

SWIFT - Show Current Location and Update Location in a MKMapView

Current Location and Update Location in a MKMapView in swift


Question :  I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).



You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}
NOTE: If your target is iOS 8, you must include the NSLocationAlwaysUsageDescription key in your Info.plist to get the location services to work.
Read More