Json:在Swift中将图像保存到核心数据中

时间:2015-02-01 00:57:12

标签: ios json swift core-data sendasynchronousrequest

我现在卡住了一点点。首先,我的代码如下,

import UIKit
import CoreData

class ViewController: UIViewController {

var eTitles : [String] = []
var jTitles : [String] = []
var pCategories : [String] = []
var imgPaths : [String] = []


override func viewDidLoad() {

    super.viewDidLoad()

    let url = NSURL(string: "http://localhost:8888/post.php")
    let allData = NSData(contentsOfURL: url!)
    let allJsonData : AnyObject! = NSJSONSerialization.JSONObjectWithData(allData!, options: NSJSONReadingOptions(0), error: nil)

    if let json = allJsonData as? Array<AnyObject>{

        //println(json)

        for index in 0...json.count-1{

            let post : AnyObject? = json[index]

            //println(post)
            let collection = post! as Dictionary<String, AnyObject>

            //println(collection)

            //println(collection["Eng_Title"])


            var eTitle : AnyObject?  = collection["Eng_Title"]
            var jTitle : AnyObject? = collection["Jam_Title"]
            var pCategory : AnyObject? = collection["Category"]
            var imgPath : AnyObject? = collection["Category_Img"]



            eTitles.append(eTitle as String)
            jTitles.append(jTitle as String)
            pCategories.append(pCategory as String)
            imgPaths.append(imgPath as String)

        }

    }



    println(eTitles)
    println(jTitles)
    println(pCategories)
    println(imgPaths)

    for var i = 0; i < pCategories.count; i++
    {

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

        let managedContext = appDelegate.managedObjectContext!
        let entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: managedContext)!
        let category = Category(entity: entity, insertIntoManagedObjectContext:managedContext)

        category.title = pCategories[i]
        category.path = fetchImg(imgPaths[i])
        appDelegate.saveContext()


        let en = NSEntityDescription.entityForName("Post", inManagedObjectContext: managedContext)!
        let post = Post(entity: en, insertIntoManagedObjectContext:managedContext)

        post.jtitle = jTitles[i]
        post.etitle = eTitles[i]
        post.category = category
        appDelegate.saveContext()

    }

}



func fetchImg(path : String) -> String{

    var urlWebView = NSURL(string: path)!
    println(urlWebView)
    var requestWebView = NSURLRequest(URL: urlWebView)
    var saveP : String = ""


    NSURLConnection.sendAsynchronousRequest(requestWebView, queue: NSOperationQueue.mainQueue(), completionHandler: {

        response, data, error in

        if error != nil {

            println("There was an error")
          } 
         else {

           // let musicFile = (data: data)

            var documentsDirectory:String?
            var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

            if paths.count > 0 {
                documentsDirectory = paths[0] as? String
                var savePath = documentsDirectory! + "/" + NSUUID().UUIDString + ".jpg"

                println(savePath)
                saveP = savePath

                NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)


            }

        }

    })

   return saveP
}


override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

    }


}

每次我运行这个应用程序时,它都停在这一行:

  

NSURLConnection.sendAsynchronousRequest(requestWebView,queue:NSOperationQueue.mainQueue(),completionHandler:{

(我在这里要做的是解析Json数据并将其放入数组,然后将其保存到CoreData中。问题是 fetchImg()函数。 我正在尝试将来自Json数据的路径传递给此函数,该函数从Web获取实际图像,创建路径并将数据保存到设备上,并返回实际保存图像的路径。)< / p>

有什么建议吗?

对不起我糟糕的英文解释!!!

谢谢!

0 个答案:

没有答案