1

I’m now stuck little bit. First, my code is as follows,

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.

    }


}

Everytime I run this app, it stops at this line :

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

(What I’m trying to do here is to parse Json data and put it into array, and then save it into CoreData. The problem is fetchImg() function. I’m trying to pass paths, which come from Json data, to this function, and the function fetch real images from web, create a path and save the data onto device, and return the path to which images actually are saved.)

Any advice?

Sorry for my poor Eng explanation!!!

Thanks!

soumya
  • 3,801
  • 9
  • 35
  • 69
Gunther
  • 21
  • 3
  • If I had to guess, which any answers will be given the lack of information. I'd guess that the URL being passed in isn't a valid URL, probably because it's partial and/or relative. What is the URL? What is the error when it crashes? And, fwiw, this isn't saving the images in CoreData, which is actually a good thing. – David Berry Feb 01 '15 at 01:49
  • Also, sendAsyncronousRequest sends a request, well.... Asyncronously, which means the result isn't available at the return statement, so this routine will always return an empty string. – David Berry Feb 01 '15 at 01:51
  • Thanks for the reply!!! The URL must be valid...something like: "http://localhost:8888/img/20140501_041438713_iOS.jpg" – Gunther Feb 01 '15 at 02:16
  • Before the above URL, there is "http://" – Gunther Feb 01 '15 at 02:21
  • There is no error message on console, just (lldb) – Gunther Feb 01 '15 at 02:22
  • So should I use syncronousRequest? – Gunther Feb 01 '15 at 02:24

0 Answers0