Monday, November 16, 2015

How to download an online text file from Google drive

Update August 13, 2017: Xcode 8.3.3/Swift 3.1.
Original Post November 15, 2016: Xcode 7.1.1/Swift 2.1:

This example shows how to download an online text file from Google drive to an iOS app. This example may also be used to for any text content on the web, such as open data in JSON format.

1. Create a file called test with its content as:

abc

2. Upload file test to Google drive. 

Right click on the file and select "Share...".











Select "Copy link":

The link should be in this format:

https://drive.google.com/open?id=ABCDE...123

3.  Convert the sharing URL to a direct URL:

https://drive.google.com/uc?export=download&id=ABCDE...123

4. Modify the code below in ViewController.swift:

Update August 13, 2017: Xcode 8.3.3/Swift 3.1.

override func viewDidLoad() {
    super.viewDidLoad()
    
    let urlString = "https://drive.google.com/uc?export=download&id=ABCDE...123" 
    
    let url = URL(string: urlString)
    
    var webString : String = ""
    
    do {
        webString = try String(contentsOf: url!)
    } catch {
        print("Error")
    }
    print(webString)

}


Original Post November 15, 2016: Xcode 7.1.1/Swift 2.1:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://drive.google.com/uc?export=download&id=ABCDE...123"
        
        let url = NSURL(string: urlString)

        NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
            
            //Convert NSData to NSString.
            let webString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(webString!)
            
        }.resume()

    }

Related Information

Print out JSON content in Swift playground
Open an internet image and create a button with underline title

Wednesday, November 11, 2015

Pick a photo from the device album and email it as attachment

This post is written with Xcode 7.1/Swift 2.1.

Edit ViewController.swift as below:

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    var myUIImage : UIImage!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRectMake(70, 100, 200, 20))
        button.setTitle("Pick a Photo", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "photoAlbum:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
    }
    
    func photoAlbum(sender: UIButton) {
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) {
            let pickerController = UIImagePickerController()
            pickerController.delegate = self
            self.presentViewController(pickerController, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        myUIImage = image
        picker.dismissViewControllerAnimated(true, completion: {
            dispatch_async(dispatch_get_main_queue(), {
                self.emailSetup()
            })
        })

    }
    
    func emailSetup() {
        
        let myController = MFMailComposeViewController()
        myController.mailComposeDelegate = self
        myController.setSubject("My Photo")
        myController.setMessageBody("Picked from my photo album.", isHTML: false)
        myController.setToRecipients(["mymail@mymail.com"])
        
        let imageData = UIImagePNGRepresentation(myUIImage)
        myController.addAttachmentData(imageData!, mimeType: "image/jpeg", fileName: "image")
        
        self.presentViewController(myController, animated: true, completion: nil)
    }
    
    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        if result.rawValue == MFMailComposeResultSent.rawValue {
            self.dismissViewControllerAnimated(false, completion: {
                
                dispatch_async(dispatch_get_main_queue(), {
                
                    let alertController = UIAlertController(title: "", message: "Mail Sent!", preferredStyle: UIAlertControllerStyle.Alert)
                    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            
                    self.presentViewController(alertController, animated:true, completion:nil)
                })
            })
        }
        
    }

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

}

Related Posts:

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, November 9, 2015

scrollViewDidScroll - Pull up table to refresh content and change the table background color

Update: December 10, 2016 (Xcode 8.1 and Swift 3.0.1)

Original Post: November 9, 2015

This example shows how to:

1. Refresh the table view by adding ten extra rows while pulling the table up to the bottom.
2. Change the table background color for every 10 rows.

Note: This example does not include the activity indicator.

Edit ViewController.swift as below:

Xcode 8.1 and Swift 3.0.1:


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView : UITableView!
    var tableRowNumber : Int = 10
    
    //Colors used in the table
    var colorArray = [UIColor.yellow, UIColor.orange, UIColor.cyan, UIColor.lightGray, UIColor.white]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: 300))

        tableView.dataSource = self
        tableView.delegate = self
        
        //Disable the default bouncing feature.
        tableView.bounces = false
        
        view.addSubview(tableView)
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableRowNumber
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "Row \(indexPath.row)"
        
        //Change the table background color for every 10 rows.
        let color = colorArray[(indexPath.row/10)%colorArray.count]
        cell.backgroundColor = color
        
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //If we reach the end of the table.
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            //Add ten more rows and reload the table content.
            tableRowNumber += 10
            tableView.reloadData()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Original Post: November 9, 2015

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView : UITableView!
    var tableRowNumber : Int = 10
    
    //Colors used in the table
    var colorArray = [UIColor.yellowColor(), UIColor.orangeColor(), UIColor.cyanColor(), UIColor.lightGrayColor(), UIColor.whiteColor()]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRectMake(0, 30, view.bounds.width, 300))
        tableView.dataSource = self
        tableView.delegate = self
        
        //Disable the default bouncing feature.
        tableView.bounces = false
        
        view.addSubview(tableView)
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableRowNumber
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "Row \(indexPath.row)"
        
        //Change the table background color for every 10 rows.
        let color = colorArray[(indexPath.row/10)%colorArray.count]
        cell.backgroundColor = color
        
        return cell
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //If we reach the end of the table.
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            //Add ten more rows and reload the table content.
            tableRowNumber += 10
            tableView.reloadData()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:


==========================
Related Post:

Sunday, November 8, 2015

iOS Chinese font comparison: PingFang with various weights 以iOS程式顯示並比較六種不同粗細變化的「蘋方」字體

Update: August 3, 2017 (Swift 3.1 + Xcode 8.3.3)

Original Post: November 8, 2015 (Swift 2)

This post shows how to list the PingFang TC(Traditional Chinese) font with 6 different weights in a table for comparison.

蘋果公司於9月正式推出的iOS9及OS X 10.11 El Capitan (酋長巨石)中,新增了「蘋方」中文字型,有正體(TC)、香港(HK)及簡體(SC)三個版本,每個版本皆有6種不同的粗細變化。

以下的Swift程式以表格列出不同粗細的「蘋方」字體:

ViewController.swift

Update: August 3, 2017 (Swift 3.1 + Xcode 8.3.3)


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    //font names
    let fontArray : [String] = [".PingFangTC-Ultralight",".PingFangTC-Thin",".PingFangTC-Light",".PingFangTC-Regular",".PingFangTC-Medium",".PingFangTC-Semibold"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: view.bounds.height-50))
        tableView.dataSource = self
        tableView.delegate = self
        
        //Do not draw line separators for empty cells.
        tableView.tableFooterView = UIView()
        
        view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "蘋方字型測試 正體"
        cell.textLabel?.font = UIFont(name: fontArray[indexPath.row], size: 28)
        cell.textLabel?.textAlignment = NSTextAlignment.center
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


Original Post: November 8, 2015 (Swift 2)

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    //font names
    let fontArray : [String] = [".PingFangTC-Ultralight",".PingFangTC-Thin",".PingFangTC-Light",".PingFangTC-Regular",".PingFangTC-Medium",".PingFangTC-Semibold"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: CGRectMake(0, 50, view.bounds.width, view.bounds.height-50))
        tableView.dataSource = self
        tableView.delegate = self
        
        //Do not draw line separators for empty cells.
        tableView.tableFooterView = UIView()
        
        view.addSubview(tableView)
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "蘋方字型測試 正體"
        cell.textLabel?.font = UIFont(name: fontArray[indexPath.row], size: 30)
        
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


結果如下:



相關資訊:

在樹莓派上安裝中文字型 Install Chinese Fonts with Raspberry Pi
Google 推新版字體網站,共 804 字體供大家免費取用!
Google Fonts
解決字體顯示問題!蘋果、Google、微軟、Adobe 攜手開發字體(inside.com.tw)