Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Sunday, May 21, 2017

Convert an Integer Array to a String

The code below shows how to convert an integer array to a string in Swift 3.1 with Xcode 8.3.1 Playground.

let arrayInt = [1, 2, 3, 4, 5]
let string = "\(arrayInt)"
print(string)

Reference:

How can I convert an Int array into a String? array in Swift

Conversion from Numbered Musical Notation to Musical Note Letters

The code below converts Numbered Musical Notation (簡譜) to musical note letters using Xcode 8.3.2 playground in Swift 3.1. Techniques used in the code involves:

1. Separating a string into an array
2. Type casting each array element into an integer

3. Converting the numerical notation into a matched letter
4. Joining all letters into a single string

//Twinkle, Twinkle, Little Star 一閃一閃亮晶晶
let numberedNotation = "1 1 5 5 6 6 5"

//1. Separating a string into an array let numberedNoteArray = numberedNotation.components(separatedBy: " ")

let lookupTable = ["C","D","E","F","G","A","B"]

var noteArray = [String]()

for note in numberedNoteArray {
    //2. Type casting each array element into an integer
    let noteInt = Int(note)!

    //3. Converting the numerical notation into a matched letter
    let noteChar = lookupTable[noteInt-1]
    noteArray.append(noteChar)
}

//4. Joining all letters into a single string let noteString = noteArray.joined(separator: " ")

print("\(noteString)")

Result:

C C G G A A G

Saturday, March 12, 2016

Convert NSData/[UInt8] to Base64 in Swift

Update - May 19, 2017 with Swift 3.1 (Xcode 8.3.2)

The code below shows how to convert String/NSData/[UInt8] to base64 data. The code involves two parts:

1. Conversion of NSData to base64 and then decoding the base64 data:

String -> NSData -> base64 NSData -> NSData -> NSString -> String

2. Conversion of [UInt8] to base64 and then decoding the base64 data:

String -> [UInt8] -> NSData -> base64 NSData -> NSData -> NSString



Swift code:

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)

let myString = "This is my string."

//1. Convert String to base64
//Convert string to NSData
let myNSData = myString.data(using: String.Encoding.utf8)! as NSData

//Encode to base64
let myBase64Data = myNSData.base64EncodedData(options: NSData.Base64EncodingOptions.endLineWithLineFeed)

//Decode base64
let resultData = NSData(base64Encoded: myBase64Data, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!

//Convert NSData to NSString
let resultNSString = NSString(data: resultData as Data, encoding: String.Encoding.utf8.rawValue)!

//Convert NSString to String
let resultString = resultNSString as String

print(resultString)

//2. Convert [UInt8] to base64
//Convert string to [UInt8]
let array : [UInt8] = Array(myString.utf8)

//Convert [UInt8] to NSData
let data = NSData(bytes: array, length: array.count)

//Encode to base64
let base64Data = data.base64EncodedData(options: NSData.Base64EncodingOptions.endLineWithLineFeed)

//Decode base64
let newData = NSData(base64Encoded: base64Data, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!

//Convert NSData to NSString
let newNSString = NSString(data: newData as Data, encoding: String.Encoding.utf8.rawValue)!

print(newNSString)

Original Post: March 12, 2016 with Swift 2.1

//1. Convert String to base64
//Convert string to NSData
let myData = myString.dataUsingEncoding(NSUTF8StringEncoding)!
        
//Encode to base64
let myBase64Data = myData.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
        
//Decode base64
let resultData = NSData(base64EncodedData: myBase64Data, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
        
//Convert NSData to NSString
let resultNSString = NSString(data: resultData, encoding: NSUTF8StringEncoding)!

//Convert NSString to String
let resultString = resultNSString as String
        
print(resultString)
        
//2. Convert [UInt8] to base64
//Convert string to [UInt8]
let array : [UInt8] = Array(myString.utf8)
        
//Convert [UInt8] to NSData
let data = NSData(bytes: array, length: array.count)
        
//Encode to base64
let base64Data = data.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
        
//Decode base64
let newData = NSData(base64EncodedData: base64Data, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
        
//Convert NSData to NSString
let newNSString = NSString(data: newData, encoding: NSUTF8StringEncoding)!
        
print(newNSString)


More Information:

Conversion between String, NSString, NSData and [UInt8] array in Swift

Monday, February 22, 2016

Conversion between String, NSString, NSData and [UInt8] array in Swift

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)

The code below shows how to convert a string to a UInt8 array and then back to string. The code includes:

1. Step-by-step conversion between the String, NSString, NSData, and [UInt8] in this procedure:

String -> NSString -> NSData -> [UInt8] -> NSData -> NSString -> String

2. Direct conversion between String and [UInt8]:

String -> [UInt8] -> String

Swift Code:

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)

let myString = "This is my string."


//1.Conversion between the String, NSString, NSData, and [UInt8]
//Convert String to NSString
let myNSString = myString as NSString

//Convert NSString to NSData
let myNSData = myNSString.data(using: String.Encoding.utf8.rawValue)!

//Convert NSData to [UInt8] array
let myArray = [UInt8](myNSData)

//Convert [UInt8] to NSData
let resultNSData = NSData(bytes: myArray, length: myArray.count)

//Convert NSData to NSString
let resultNSString = NSString(data: resultNSData as Data, encoding: String.Encoding.utf8.rawValue)!

//Convert NSString to String

let resultString = resultNSString as String

print(resultString)

//2.Direct conversion between the String and [UInt8]
//Directly convert string to [UInt8]
let directArray : [UInt8] = Array(myString.utf8)

//Directly convert [UInt8] to String
let directResultString = NSString(bytes: directArray, length: 
    directArray.count, encoding: String.Encoding.utf8.rawValue)! as String
print(directResultString)

Original Post: Feb. 22, 2016 with Swift 2.1



let myString = "This is my string."

//1.Conversion between the String, NSString, NSData, and [UInt8]
//Convert String to NSString
let myNSString = myString as NSString
        
//Convert NSString to NSData
let myNSData = myNSString.dataUsingEncoding(NSUTF8StringEncoding)!
        
//Get length of [UInt8]
let length = myNSData.length
        
//Convert NSData to [UInt8] array
var myArray = [UInt8](count: length, repeatedValue: 0)
myNSData.getBytes(&myArray, length: length)
        
//Convert [UInt8] to NSData
let resultNSData = NSData(bytes: &myArray, length: length)
        
//Convert NSData to NSString
let resultNSString = NSString(data: resultNSData, encoding: NSUTF8StringEncoding)!
        
//Convert NSString to String

let resultString = resultNSString as String

print(resultString)

//2.Direct conversion between the String and [UInt8]
//Directly convert string to [UInt8]
let directArray : [UInt8] = Array(myString.utf8)
        
//Directly convert [UInt8] to String
let directResultString = NSString(bytes: directArray, length: 
directArray.count, encoding: NSUTF8StringEncoding) as! String

Tuesday, November 10, 2015

Print the first character of a string in a color circle

The following code is written with Xcode 7.1 (Swift 2.1) and tested with Xcode 6.4 (Swift 1.2). The first character of a string is printed in a color circle.

ViewController.swift:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let offsetY : CGFloat = 100
        let labelCircleX : CGFloat = 100
        let labelX : CGFloat = 200
        
        let colorArray = [UIColor.orangeColor(), UIColor.blueColor(), UIColor.redColor()]
        let stringArray = ["Apple", "蘋果", "tv"]
        //Strings can include Unicode chacters.
        //The Apple logo character can be typed using [option]+[shift]+[K]
        //Unfortunately, the Apple logo character  cannot be seen in windows.
        
        for item in 0...2 {
            
            //Convert Int item to CGFloat using CGFloat(item).
            let labelCircleY : CGFloat = offsetY*CGFloat(item+1)
            let labelY : CGFloat = labelCircleY + 20
            createCharacterInCircle(labelCircleX, y: labelCircleY, text: stringArray[item], color: colorArray[item])
            createLabel(labelX, y: labelY, text: stringArray[item])
        }
    }
    
    func createCharacterInCircle(x: CGFloat, y: CGFloat, text: String, color: UIColor) {
        
        //Get the first character of string "text" and convert it to string.
        //"text" can be a string with Unicode characters.
        let firstChar = "\(text.characters.first!)" //Swift 2.1
        //let firstChar = "\(Array(text)[0])" //Swift 1.2
        
        let labelCircleSize : CGFloat = 70
        let labelCircle = UILabel(frame: CGRectMake(x, y, labelCircleSize, labelCircleSize))
        
        //Color Settings
        labelCircle.backgroundColor = color
        labelCircle.textColor = UIColor.whiteColor()
        
        //Text Settings
        labelCircle.text = firstChar
        labelCircle.font = UIFont(name: ".HelveticaNeueInterface-Bold", size: 30)
        labelCircle.textAlignment = NSTextAlignment.Center
        
        //Circle Settings
        labelCircle.layer.cornerRadius = labelCircleSize/2
        labelCircle.layer.masksToBounds = true
        
        //Border Settings
        labelCircle.layer.borderColor = UIColor.blackColor().CGColor
        labelCircle.layer.borderWidth = 3
        view.addSubview(labelCircle)
    }
    
    func createLabel(x: CGFloat, y: CGFloat, text: String) {
        let label = UILabel(frame: CGRectMake(x, y, 100, 25))
        label.text = text
        view.addSubview(label)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:


Monday, October 19, 2015

componentsSeparatedByCharactersInSet and join - Remove specific characters in a string

In this example, parenthesis "()" and white space " " are removed. For Xcode 6.4 (Swift 1.2):

let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")

//Separate phoneOld by unwanted characters in charSet and form an array.
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet) as! [String]


//Join all elements of phoneArray together without inserting any character between the elements.
let phoneNew = join("", phoneArray)


Results:



For Swift 2:

let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet)

let phoneNew = phoneArray.joinWithSeparator("")

Related string function:

Wednesday, October 14, 2015

Open an internet image and create a button with underline title

Update: July 12, 2017 - Xcode 8.3.3 + Swift 3.1

Original Post: Xcode 6.4 (Swift 1.2)

Note: For Xcode 7 (Swift 2), refer to the information at the bottom of this page.


How to open an image file online with an iOS app?
Simply modify ViewController.swift as below:

Update: July 12, 2017 - Xcode 8.3.3 + Swift 3.1

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //--------------------- Image ----------------------
        // URL for the web image
        let url = URL(string: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKqwWN6ru5rEMD7sT38QiCuFETD-65Hizt8k7KiS5QnWfRwydKcsX0rj6zgAezKFRm-GWGjJWBHWjoa7pKy5ubbBtAECVwmuohkBx4zL9eK6_XP-UbtXjCcpPl9cFKsScIOtzWoN0pxD4/s1600/IMG_4809.JPG")
        let imageView = UIImageView(frame: CGRect(x: 20, y: 100, width: view.bounds.width-40, height: view.bounds.height-200))
        
        //Image data for Swift 3
        var data : Data!
        do {
            data = try Data(contentsOf: url!)
        } catch {
            print(error.localizedDescription)
            return
        }
        
        imageView.image = UIImage(data: data)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.scaleAspectFit
        
        view.addSubview(imageView)
        
        
        //--------------------- Link Button ----------------------
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
        
        //Relocate the button with the center position.
        button.center = CGPoint(x: view.bounds.width/2, y: 50)
        
        //Underline the button and set the text as blue.
        let attributedString = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor.blue])
        button.setAttributedTitle(attributedString, for: UIControlState.normal)
        
        //Set the highlight color as cyan.
        let attributedStringHighlight = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor.cyan])
        button.setAttributedTitle(attributedStringHighlight, for: UIControlState.highlighted)
        
        button.addTarget(self, action: #selector(btnPressed), for: UIControlEvents.touchUpInside)
        view.addSubview(button)
        
    }
    
    func btnPressed() {
        let string = "http://cutecorners.blogspot.com/"
        UIApplication.shared.open(URL(string: string)!, options: [:], completionHandler: nil)//Open the URL in the browser.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Xcode 6.4 (Swift 1.2): Edit ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //--------------------- Image ----------------------
        // URL for the web image
        let url = NSURL(string: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKqwWN6ru5rEMD7sT38QiCuFETD-65Hizt8k7KiS5QnWfRwydKcsX0rj6zgAezKFRm-GWGjJWBHWjoa7pKy5ubbBtAECVwmuohkBx4zL9eK6_XP-UbtXjCcpPl9cFKsScIOtzWoN0pxD4/s1600/IMG_4809.JPG")
        
        let imageView = UIImageView(frame: CGRectMake(20, 100, view.bounds.width-40, view.bounds.height-200))
        imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        
        view.addSubview(imageView)
        
        
        //--------------------- Link Button ----------------------
        let button = UIButton(frame: CGRectMake(0, 0, 200, 20))
        
        //Relocate the button with the center position.
        button.center = CGPoint(x: view.bounds.width/2, y: 50)
        
        //Underline the button and set the text as blue.
        let attributedString = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSForegroundColorAttributeName: UIColor.blueColor()])
        button.setAttributedTitle(attributedString, forState: UIControlState.Normal)
        
        //Set the highlight color as cyan.
        let attributedStringHighlight = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSForegroundColorAttributeName: UIColor.cyanColor()])
        button.setAttributedTitle(attributedStringHighlight, forState: UIControlState.Highlighted)

        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
    }
    
    func btnPressed(sender: UIButton) {
        let string = "http://cutecorners.blogspot.com/"
        UIApplication.sharedApplication().openURL(NSURL(string: string)!)//Open the URL in the browser.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

The result:





Updated Oct. 31, 2015:  Xcode 7 (Swift 2)


While building the above code, error happens:


App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

This is because Apple has introduced App Transport Security (ATS) in iOS9, but the image link used in this example is an insecure HTTP URL. To allow this network connection, modify Info.plist by adding:



If you need secure HTTPS connections, do not use this solution. More details regarding ATS is here:


Related Information:

Apple will require HTTPS connections for iOS apps by the end of 2016