2016年4月13日 星期三

[功能]將json抓下來放進coredata

//當然前提也要先成立coredata並成立一個swift檔(create NSManagedObject Subclass)

import UIKitimport CoreDataclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
   
var result:Array<Product> = []

   
@IBOutlet weak var tableViewCore: UITableView!

   
var id_json: String = ""
   
var name_json: String = ""
   
var discount_json: String = ""



   
override func viewDidLoad() {
       
super.viewDidLoad()
         
tableViewCore.delegate = self
         
tableViewCore.dataSource = self
    
       
      
       
var url = NSURL(string: "http://appapi999.scanallgoods.com/api/Product/GetProductInfo?QR_Code=5-z2ELfceDNDseP8EGOFwu0ssxwmLpxzp-UAelTXpgTF30o24a2CvTTcOMSB8dneH0")
    
       
var data = NSData(contentsOfURL: url!)
    
       
var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error:nil)
    
       
id_json = json?.objectForKey("Product_ID") as! String
       
name_json = json?.objectForKey("Product_Name") as! String
       
discount_json = json?.objectForKey("Discount_Way") as! String
    
       
println(id_json)
       
println(name_json)
       
println(discount_json)
            
    
       
var appDele :AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
       
var context:NSManagedObjectContext = appDele.managedObjectContext!
       
var fetch:NSFetchRequest = NSFetchRequest(entityName: "Product")
       
result = context.executeFetchRequest(fetch, error: nil) as! [Product]
      
initData()
  
       
var error: NSError?
       
let fetchedResults = context.executeFetchRequest(fetch, error: &error)
           
as! [NSManagedObject]?
    
       
if let results = fetchedResults
        {
           
for (var i=0; i < results.count; i++)
            {
               
let single_result = results[i]
               
let name_data = single_result.valueForKey("name") as! String
               
let id_data = single_result.valueForKey("id") as! String
               
let discount_data = single_result.valueForKey("discount") as! String
               
println(name_data)
               
println(id_data)
               
println(discount_data)
               
//uncomment this line for adding the stored object to the core data array                //name_list.append(single_result)            }
        }
       
else
        {
           
println("cannot read")
        }

    
        
tableViewCore.reloadData()
    
    
       
// Do any additional setup after loading the view, typically from a nib.    }

   
func initData(){
       
var appDele :AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
       
var context:NSManagedObjectContext = appDele.managedObjectContext!
       
var fetch:NSFetchRequest = NSFetchRequest(entityName: "Product")
       
var product:Product
    
    
        product =
NSEntityDescription.insertNewObjectForEntityForName("Product", inManagedObjectContext: context) as! Product
    
        product.
name = name_json
       product.
id = id_json
        product.
discount = discount_json
        context.save(nil)    


    }

   
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
return result.count
    }

   
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
let cell: UITableViewCell = tableViewCore.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell
        cell.
textLabel!.text = result[indexPath.row].name
        cell.
detailTextLabel?.text=result[indexPath.row].discount
       
return cell
    }



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


}

沒有留言:

張貼留言