2015/02/12

Swift IOS Read project file

Project內有一個檔案『test.txt』,裡面文字檔如下圖
讀取檔案內的文字,可透過NSString建構子將文字讀出

首先先透過下面這個方法取得Bundle內指定的檔案
NSBundle.mainBundle().pathForResource


判斷該String是否為nil,如果是就回傳空字串
if(file == nil){
            return ""
        }

如果不是就傳回檔案中的文字,並以UTF8去編碼
        return NSString(contentsOfFile: file!, encoding: NSUTF8StringEncoding, error: nil)



Code:
//
//  ViewController.swift
//  Sample
//
//  Created by C.Y.Fang on 2/12/15.
//  Copyright (c) 2015 C.Y.Fang. All rights reserved.
//

import UIKit

class ViewController: UIViewController {


    
    override func viewDidLoad() {
        super.viewDidLoad()
        println(getProjectFileContent("test", fileExtension: "aa"))
        println(getProjectFileContent("test", fileExtension: "txt"))
    }

    
    func getProjectFileContent(filename:String, fileExtension : String?) -> String? {
        var file = NSBundle.mainBundle().pathForResource(filename, ofType: fileExtension)
        if(file == nil){
            return ""
        }
        
        return NSString(contentsOfFile: file!, encoding: NSUTF8StringEncoding, error: nil)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


執行結果:

沒有留言:

張貼留言