Friday, 18 December 2015

SWIFT: INSTALL CocoaPods USING TERMINAL

You first need to install CocoaPods. Fortunately, CocoaPods is built on Ruby, which ships with all recent versions of Mac OS X. This has been the case since OS X 10.7.
Open Terminal and enter the following command:
sudo gem install cocoapods
Enter your password when requested. The Terminal output should look something like this:
Lastly, enter this command in Terminal to complete the setup:
pod setup --verbose

This process will likely take a few minutes as it clones the CocoaPods Master Specs repository into~/.cocoapods/ on your computer.
The verbose option logs progress as the process runs, allowing you to watch the process instead of seeing a seemingly “frozen” screen.
Awesome, you’re now setup to use CocoaPods!
How to Use CocoaPods with Swift
PLEASE FOLLOW THIS LINK :
http://www.raywenderlich.com/97014/use-cocoapods-with-swift

Thursday, 17 December 2015

SWIFT: GENERATE DEVICE TOKEN FOR PUSHNOTIFICATIONS

GENERATE DEVICE TOKEN FOR PUSHNOTIFICATIONS IN SWIFT


IN Appdelegate.swift

create these methods:


    func initializeNotificationServices() -> Void {
        
        let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        
        // This is an asynchronous method to retrieve a Device Token
        // Callbacks are in AppDelegate.swift
        // Success = didRegisterForRemoteNotificationsWithDeviceToken
        // Fail = didFailToRegisterForRemoteNotificationsWithError
        UIApplication.sharedApplication().registerForRemoteNotifications()
    }
    
    
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let deviceTokenStr = convertDeviceTokenToString(deviceToken)
        // ...register device token with our Time Entry API server via REST
        print("dynamic Device Token:    \(deviceTokenStr)")  
    }
    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("Device token for push notifications: FAIL -- ")
        print(error.description)
    }


Call this function "initializeNotificationServices()" where ever you want like below

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.initializeNotificationServices()

Friday, 11 December 2015

SWIFT: Play youtube video in WebView

Play youtube video in WebView



First Drag this "Assets" folder in to your project 

check "Copy items if need"
check "Create folder reference"


The "Assets" folder must be in blue color
https://drive.google.com/drive/u/0/folders/0B9iu5I479ob8RlAwVFRsWVFXV1E


In bridge-header.h page  write this

#import "YTPlayerView.h"


class videoViewController: ViewController{

 var playerView: YTPlayerView = YTPlayerView()

 override func viewDidLoad() {
        super.viewDidLoad()
    playerView.frame = CGRectMake(15, 20, self.view.frame.width - 30, 200)
        self.view.addSubview(playerView)

        let embedId = self.extractYoutubeIdFromLink("https:\/\/www.youtube.com\/watch?v=1HPcUBySv6c")
        self.playerView.layer.borderWidth = 3
        self.playerView.layer.borderColor = UIColor.lightGrayColor().CGColor
        self.playerView.loadWithVideoId(embedId)
}

    func extractYoutubeIdFromLink(link: NSString) ->String{
        let regexString = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
        do {
            let regex = try NSRegularExpression(pattern: regexString, options: NSRegularExpressionOptions.CaseInsensitive)
            var array = NSArray()
            array = regex.matchesInString(link as String, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0,link.length))
            if (array.count > 0) {                
                let result = array.firstObject;                
                let embedId = link.substringWithRange(result!.range)                
                return embedId                
            }           
            
        } catch{
            let k:String? = nil
            return k!
        }
        let k:String? = nil
        return k!
    }
}







Wednesday, 9 December 2015

Push notification link SWIFT

https://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/

Tuesday, 8 December 2015

SWIFT: BUTTTON CLICK CHANGE THE TOUCH EFFECT

func fadeButton(button:UIButton){
        UIView.animateWithDuration(3.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            button.alpha = 0.3
            }, completion: {
                (finished: Bool) -> Void in
                // Fade in
                UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                    button.alpha = 1.0
                    }, completion: nil)
        })

    }

SWIFT: GET DATA FROM WEBSERVICE

GET JSON DATA  OR ARRAY DATA FROM SERVICE IN SWIFT 2.0

 let url =  " "

/*-------------------------- Get Json data -------------------------------------------------*/

func loadWebServiceData(){
        self. fillTheData(url, callback: self.jsonData, errorCallback: self.showError)
    }

func fillTheData(url: String?, callback: (NSDictionary) -> Void, errorCallback: (Void) -> Void){
        if url != nil{            
            if let nsurl = NSURL(string: url!){
                let request = NSURLRequest(URL: nsurl)
                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{response, data, error -> Void in
                    if error == nil{
                        if let dataDict = self.parseJSON(data!){
                            callback(dataDict)
                        }else{
                            errorCallback()
                        }
                    }else{
                        errorCallback()
                    }
                })
            }else{
                errorCallback()
            }
        }else{
            errorCallback()
        }
    }


func parseJSON(data: NSData)->NSDictionary?{
        do {
            let dataDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
            return dataDict
        } catch{
            //ErrorHandler.Instance.showError()
            return nil
        }
    }

func jsonData(data: NSDictionary){
  print("this is an json data:   \(data)")
}

/*-------------------------- Get Array data -------------------------------------------------*/

func loadWebServiceData(){
        self.fillTheDataFromArray(url, callback: self.arrayData, errorCallback: self.showError)
    }

func fillTheDataFromArray(url: String?, callback: (NSArray) -> Void, errorCallback: (Void) -> Void){
        if url != nil{
            if let nsurl =  NSURL(string: url!){
                let request = NSURLRequest(URL: nsurl)
                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{response, data, error -> Void in
                    if error == nil{
                        if let dataArray = self.parseJSONArray(data!){
                            callback(dataArray)
                        }else{
                            errorCallback()
                        }
                    }else{
                        errorCallback()
                    }
                })
            }else{
                errorCallback()
            }
        }else{
            errorCallback()
        }
    }

func parseJSONArray(data: NSData)->NSArray?{
        do {
            let dataDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) asNSArray
            return dataDict
        } catch let error as NSError {
            print("json error: \(error.localizedDescription)")
            return nil
        }
    }




func showError(){
   print("error occured")
}

func arrayData(data: NSArray){
  print("this is an array data:   \(data)")
}

SWIFT: DRAG AND DROP UILABELS IN TO UITEXTVIEW

DRAG AND DROP UILABELS IN TO UITEXTVIEW

THE BELOW SCREENSHOTS ARE TAKEN FROM FROM MY APP TO SHOW YOU AN EXAMPLE.

HERE IN MY PROJECT I HAVE TO REASSEMBLE THE WORDS IN TO CORRECT SENTENCE BY DRAG AND DROP METHOD

HERE  MULTIPLE UILABELS ARE CREATED WITH USERINTERACTION ENABLED TO IT AND A UITEXTVIEW TO DROP LABELS

AFTER DROPING THE LABELS IN TO REQUIRED VIEW I AM DISABLING THE DROPPED LABELS AND CHANGING THE STYLE.

HERE I AM WRITING THE CODE ONLY FOR DRAGLABELS AND DROPVIEW:
FIND THE CODE BELOW:

                            


                         




class jumbleViewController: ViewController, UITextViewDelegate{
      var dragObject = UILabel()
    var touchOffset = CGPoint()
    var homePosition = CGPoint()
    var sampleY: CGFloat = 0
    var sampleX: CGFloat = 0
    var crosstextIcon = UIButton()
    var selectedRadionButtonIndex = 0
    let dropBoxView = UIView()
    let dragTextBox = UITextView()
    let hideText = UITextField()
    let words = ["delhi", "is", "from", "sagar"]
       
    override func viewDidLoad() {
         super.viewDidLoad()
        dropBoxView.frame = CGRectMake(20, 0, self.view.frame.width - 40, 60)
        dropBoxView.backgroundColor = UIColor.grayColor()
        dropBoxView.layer.cornerRadius = 7
       
        let textParentView = UIView()
        textParentView.frame = CGRectMake(7, 7, dropBoxView.frame.width - 14, dropBoxView.frame.height - 14)
        textParentView.backgroundColor = UIColor.whiteColor()
        dropBoxView.addSubview(textParentView)
       
       
        dragTextBox.frame = CGRectMake(0, 0, textParentView.frame.width - (crossBtn.frame.width + 10), textParentView.frame.height)
        self.styleTextField(dragTextBox)       
        textParentView.addSubview(dragTextBox)       
       
        hideText.frame = CGRectMake(0, 0, textParentView.frame.width, textParentView.frame.height)
        let dragPlaceText = "Drag Here"
        hideText.placeholder = "     \(dragPlaceText)"
        hideText.enabled = false
        hideText.backgroundColor = UIColor.whiteColor()
        textParentView.addSubview(hideText)
        self.view.addSubview(dropBoxView)

         var pos_x: CGFloat = 20
         var pos_y: CGFloat = 30
          for word in words{
                let draglabel = UILabel()
                draglabel.frame = CGRectMake(pos_x, pos_y, 0, 0)                
                draglabel.text = "\(word)"
                draglabel.backgroundColor = UIColor.greenColor()
                draglabel.textColor = UIColor.whiteColor()
                draglabel.font = UIFont(name: "Lato", size: 15)
                draglabel.numberOfLines = 0
                draglabel.sizeToFit()
                draglabel.layer.cornerRadius = 5
                draglabel.layer.masksToBounds = true                
                draglabel.frame.size.height = 30
                draglabel.frame.size.width += 10
                draglabel.textAlignment = .Center
                let labWidth = draglabel.frame.origin.x + draglabel.frame.width
                let pViewWidth = self.view.frame.width - 40
                
                if(labWidth > pViewWidth){
                    pos_x = 20
                    pos_y = pos_y + draglabel.frame.height + 10                    
                    draglabel.frame.origin.x = pos_x
                    draglabel.frame.origin.y = pos_y
                    pos_x = pos_x + draglabel.frame.width + 15                    
                }
                else{
                    draglabel.frame.origin.x = pos_x
                    draglabel.frame.origin.y = pos_y
                    pos_x = pos_x + draglabel.frame.width + 15
                    pos_y = draglabel.frame.origin.y                    
                }         
                
                draglabel.userInteractionEnabled = true    // It is must and should for label            
                self.view.addSubview(draglabel)
              dropBoxView.frame.origin.ydraglabel.frame.origin.y + draglabel.frame.height + 20
            }
         }
     
        func textViewDidBeginEditing(textView: UITextView) {
        self.view.endEditing(true)
    }

     /*  ------------------------------ Delegate Touch Methods -----------------------------*/

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if touches.count == 1{
            if let touch = touches.first {
                let touchPoint = touch.locationInView(self.view)
                for iView in self.view.subviews{
                    if ((iView as? UILabel) != nil){
                        if (touchPoint.x > iView.frame.origin.x + sampleX &&
                            touchPoint.x < iView.frame.origin.x + iView.frame.size.width + sampleX &&
                            touchPoint.y > iView.frame.origin.y + sampleY &&
                            touchPoint.y < iView.frame.origin.y + iView.frame.size.height + sampleY)
                        {
                            self.dragObject = (iView as? UILabel)!
                            self.touchOffset = CGPointMake(touchPoint.x - iView.frame.origin.x + sampleX,
                                touchPoint.y - iView.frame.origin.y + sampleY);
                            self.homePosition = CGPointMake(sampleX + iView.frame.origin.x,
                                iView.frame.origin.y + self.sampleView.frame.origin.y + sampleY)
                            self.view.bringSubviewToFront(self.dragObject)
                        }
                    }
                }
                
            }
            
        }
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touchPoint = touches.first?.locationInView(self.view)
        if(self.dragObject.text == "" || self.dragObject.text == nil || self.dragObject.backgroundColor == UIColor.lightGrayColor()){
            return
        }
        let newDragObjectFrame = CGRectMake(touchPoint!.x - touchOffset.x,
            touchPoint!.y - touchOffset.y,
            self.dragObject.frame.size.width,
            self.dragObject.frame.size.height)
        self.dragObject.frame = newDragObjectFrame
    }



IN THIS LAST "TOUCHESENDED" FUNCTION  

I AM CHECKING WHETHER DISABLE DRAG LABEL IS TOUCHED OR NOT IF TOUCHED THEN BREAK IT

THIS IS IMPORTANT HERE I WILL BE TAKING THE X , Y, WIDTH AND HEIGHT VALUES OF DRAG OBJECT AND COMPARE WITH DROP VIEW WHETHER IT IS IN OR OUT OR UP ON IT

IF IT IS IN OR UP ON DROP VIEW  I AM ALLOWING IN TO IF LOOP 
  1.  I AM COMBINING THE DRAGOBJECT TEXT AND TEXTVIEW TEXT
  2. AS DATA IN TEXTVIEW INCREASES THE TEXTVIEW ALSO INCREASES
  3. THE HIDE TEXTBOX IS HIDDEN WHICH IS USED FOR PLACEHOLDER
  4. REQUIRED DRAGLABEL IS STYLED 
ELSE IF IT IS OUT OF DROP VIEW  I AM NOT ALLOWING IN TO IF LOOP 

FINALLY  I AM MAKING THE DRAGGED LABEL TO ITS ORIGINAL POSITION (HOME POSITION) 


override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touchPoint = touches.first?.locationInView(self.view)
        if(self.dragObject.text == "" || self.dragObject.text == nil || self.dragObject.backgroundColor == UIColor.lightGrayColor()){
            return
        }
        
        if (touchPoint!.x > self.dropBoxView.frame.origin.x + sampleX &&
            touchPoint!.x < self.dropBoxView.frame.origin.x + self.dropBoxView.frame.size.width + sampleX &&
            touchPoint!.y > self.dropBoxView.frame.origin.y + sampleY &&
            touchPoint!.y < self.dropBoxView.frame.origin.y + self.dropBoxView.frame.size.height + sampleY)
        {
            let text = self.dragObject.text!
            let trimedText = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            self.dragTextBox.text = self.dragTextBox.text + " " + trimedText      
            let DesFixedWidth = self.dragTextBox.frame.size.width
            self.dragTextBox.sizeThatFits(CGSize(width: DesFixedWidth, height: CGFloat.max))
            let newSize = self.dragTextBox.sizeThatFits(CGSize(width: DesFixedWidth, height: CGFloat.max))
            var newFrame = self.dragTextBox.frame
            newFrame.size = CGSize(width: max(newSize.width, DesFixedWidth), height: newSize.height)
            self.dragTextBox.frame = newFrame;
            self.dragTextBox.scrollEnabled = false
            self.dragTextBox.userInteractionEnabled = false
            if(dragTextBox.frame.height < 50){
                dragTextBox.frame.size.height = 50
            }
            
            dragTextBox.superview!.frame.size.height = dragTextBox.frame.height
            dropBoxView.frame.size.height = dragTextBox.superview!.frame.height + 14
            if(self.dragTextBox.text != "" && self.dragTextBox.text != nil){
                hideText.hidden = true
            }
            self.dragObject.backgroundColor = UIColor.lightGrayColor()
            self.dragObject.userInteractionEnabled = false
       }
        self.dragObject.frame = CGRectMake(self.homePosition.x, self.homePosition.y,
            self.dragObject.frame.size.width,
            self.dragObject.frame.size.height);
    }
}

HERE IF YOU UNDERSTAND THE CODE I AM JUST WRITTEN A LOGIC BY USING X,Y,WIDTH AND HEIGHT VALUES AND WHEN IT IS REQUIRED I JUST TAKEN THE TEXT OF DRAG LABEL, CHANGED THE COLORS OF DRAGLABEL AND AGAIN MOVING TO ITS HOME POSITION




SWIFT : Display a well positioned Horizontal and Vertical dynamically multiple objects

 Display a well positioned Horizontal and Vertical dynamically multiple objects applicable to all devices

for example here any object as "button". Follow my code. 

Here i will be displaying an array for numbers as titles for buttons and it can be highlighted by clicking on it 

class arrayStatus: NSObject {
    let title: String
    let status: String
    
    init(title: String, status: String) {
        self.title = title
        self.status = status
    }
}

class customViewController: ViewController{

var ageArray = [arrayStatus]()
let  customView = UIScrollView()

override func viewDidLoad() {
/* Here i am appending 100 numbers as stings in to an array and just for default selection i changed the status one string */

/* Here i have taken a customView as UIScrollView and i will be display the dynamic objects in it and i just added some styles to it */

/* I have created and called a custom function for displaying the objects */

for var i = 1; i <= 100; ++i{
            var ageStatus = "off"
            if(i == 24){
                ageStatus = "on"
            }
            self.ageArray.append(arrayStatus(title: String(i), status: ageStatus))
        }


        customView.frame = CGRectMake(15, 40, self.view.frame.width - 30, 50)
        self.view.addSubview(customView)
        customView.backgroundColor = UIColor.whiteColor()
        customView.layer.cornerRadius = 4
        customView.layer.borderColor = UIColor.darkGrayColor().CGColor
        customView.layer.borderWidth = 1
       
       self.displayObjects(customView)
}

 func displayObjects(tView:UIScrollView){
   
        var pos_x: CGFloat = 10
        var pos_y: CGFloat = 10

        for var i = 0; i < self.ageArray.count; ++i{
            let selectAgeButton = UIButton()
            selectAgeButton.frame = CGRectMake(pos_x, pos_y, 30, 30)
            selectAgeButton.setTitle(self.ageArray[i].title, forState: .Normal)
            selectAgeButton.setTitleColor(UIColor.greenColor(), forState: .Normal)
            selectAgeButton.layer.borderWidth = 1
            selectAgeButton.layer.borderColor = UIColor.greenColor.CGColor
            selectAgeButton.layer.cornerRadius = 5
            selectAgeButton.layer.masksToBounds = true
            selectAgeButton.addTarget(self, action: "selectAgeButtonAction:", forControlEvents: .TouchUpInside)
            
            let labWidth = selectAgeButton.frame.origin.x + selectAgeButton.frame.width
            let pViewWidth = tView.frame.width
            
            if(labWidth > pViewWidth){
                pos_x = 10
                pos_y = pos_y + selectAgeButton.frame.height + 10
                
                selectAgeButton.frame.origin.x = pos_x
                selectAgeButton.frame.origin.y = pos_y
                pos_x = pos_x + selectAgeButton.frame.width + 15
            }
            else{
                selectAgeButton.frame.origin.x = pos_x
                selectAgeButton.frame.origin.y = pos_y
                pos_x = pos_x + selectAgeButton.frame.width + 15
                pos_y = selectAgeButton.frame.origin.y
            }

            if(self.ageArray[i].status == "on"){
                selectAgeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                selectAgeButton.backgroundColor = UIColor.greenColor()
            }
            
            tView.frame.size.heightselectAgeButton.frame.origin.y + selectAgeButton.frame.height + 10
            if(tView.frame.size.height > 215){
                tView.frame.size.height = 215
                tView.contentSize.heightselectAgeButton.frame.origin.y + selectAgeButton.frame.height + 50
            }
            tView.addSubview(selectAgeButton)
        }  
}

func selectAgeButtonAction(button:UIButton){
        for sview in (button.superview?.subviews)!{
            (sview as? UIButton)?.backgroundColor = UIColor.whiteColor()
            (sview as? UIButton)?.setTitleColor(UIColor(netHex:0x0c8506), forState: .Normal)
        }
        (button as? UIButton)?.backgroundColor = UIColor(netHex:0x0c8506)
        (button as? UIButton)?.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    }
}












Setting Up Multiple App Targets in Xcode from a Single Codebase

 To create two different apps (like "Light" and "Regular") from the same codebase in Xcode, you can follow these steps b...