Playing Audio File from the directory in swift - ios

I am trying to save a audio file from a server to the users phone so they dont have to download it again its always there. I have almost everything but i am trying to test and see if the audio file actually plays after it is saved. How do i do this?
Code i have:
var urlWebView = NSURL(string: "http://domain.com//////audios////Nightmares.wav")
var requestWebView = NSURLRequest(URL: urlWebView)
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! + "/audio.wav"
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
self.audioPlayer = AVAudioPlayer(contentsOfURL: savePath, error: nil)
//tried to play it here but i cant since savePath is a string and not actually audio file
}
}
})

import UIKit
import Foundation
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var strFiles: UITextView!
var myPlayer = AVAudioPlayer()
var yourSound:NSURL?
func prepareYourSound(myData:NSData) {
myPlayer = AVAudioPlayer(data: myData, error: nil)
myPlayer.prepareToPlay()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var urlWebView = NSURL(string: "http://freewavesamples.com/files/Korg-DS-8-Rotary-Organ-C6.wav")!
var requestWebView = NSURLRequest(URL: urlWebView)
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! + "/audio.wav"
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
self.prepareYourSound(musicFile)
self.myPlayer.play()
//tried to play it here but i cant since savePath is a string and not actually audio file
// list your files from disk (documents)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let files = NSFileManager().enumeratorAtPath(documentsPath)
var myFiles:[String] = []
while let file: AnyObject = files?.nextObject() {
myFiles.append(file as String)
self.strFiles.text = "\(self.strFiles.text)\n\(file as String)"
}
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

How to manage the AVAudioPlayer isPlaying in each tableviewCell?

I have a tableview and have multiple cells in tableView.
Each cell has an item of AVAudioPlayer
And I face a problem.
I don't know how to manage the AVAudioPlayer.
When I play first AVAudioPlayer, and then play second AVAudioPlayer, the sound will overlap.
How to stop first AVAudioPlayer in my customized cell, and play second AVAudioPlayer?
Thanks.
This is my customized cell:
class TableViewCell: UITableViewCell {
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var myChatBubbleView: UIView!
#IBOutlet weak var myDateLabel: UILabel!
#IBOutlet weak var mySecondLabel: UILabel!
#IBOutlet weak var myRecordPlayerBtn: MenuButton!
private var timer:Timer?
private var elapsedTimeInSecond:Int = 0
var audioPlayer:AVAudioPlayer?
var message:ChatroomMessage?
var chatroomId:String = ""
var delegate:PlayRecordDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = defaultBackgroundColor
self.tintColor = defaultChatroomCheckButtonColor
myImageView.layer.masksToBounds = true
myImageView.layer.cornerRadius = defaultIconRadius
myChatBubbleView.backgroundColor = defaultChatGreenBubbleColor
myChatBubbleView.layer.cornerRadius = defaultButtonRadius
myDateLabel.textColor = defaultChatTimeColor
mySecondLabel.textColor = defaultChatTimeColor
mySecondLabel.isHidden = true
myRecordPlayerBtn.imageView?.animationDuration = 1
myRecordPlayerBtn.imageView?.animationImages = [
UIImage(named: "img_myRocordPlaying1")!,
UIImage(named: "img_myRocordPlaying2")!,
UIImage(named: "img_myRocordPlaying3")!
]
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func loadByMessage(_ message:ChatroomMessage, chatroomId:String) {
self.message = message
self.chatroomId = chatroomId
myRecordPlayerBtn.addTarget(self, action: #selector(recordPlay), for: .touchUpInside)
}
func resetRecordAnimation() {
self.myRecordPlayerBtn.imageView!.stopAnimating()
self.myRecordPlayerBtn.isSelected = false
}
func recordPlay(_ sender: UIButton) {
self.myRecordPlayerBtn.imageView?.startAnimating()
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(chatroomId)/Record/")
let fileName = message?.content.substring(from: 62)
let fileURL = documentsDirectoryURL.appendingPathComponent(fileName!)
if FileManager.default.fileExists(atPath: fileURL.path) {
let asset = AVURLAsset(url: URL(fileURLWithPath: fileURL.path), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
self.elapsedTimeInSecond = Int(audioDurationSeconds)
if audioPlayer?.isPlaying == true {
audioPlayer?.stop()
DispatchQueue.main.async {
self.resetTimer(second: self.elapsedTimeInSecond)
self.startTimer()
}
}
updateTimeLabel()
startTimer()
audioPlayer = try? AVAudioPlayer(contentsOf: fileURL)
audioPlayer?.delegate = self
audioPlayer?.play()
}else{
//don't have file in local
let recordUrl = URL(string: (message?.content)!)
URLSession.shared.downloadTask(with: recordUrl!, completionHandler: { (location, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("audio"),
let location = location, error == nil
else { return }
do {
try FileManager.default.moveItem(at: location, to: fileURL)
let asset = AVURLAsset(url: URL(fileURLWithPath: fileURL.path), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
self.elapsedTimeInSecond = Int(audioDurationSeconds)
DispatchQueue.main.async {
self.updateTimeLabel()
self.startTimer()
}
self.audioPlayer = try? AVAudioPlayer(contentsOf: fileURL)
self.audioPlayer?.delegate = self
self.audioPlayer?.play()
} catch {
print(error)
}
}).resume()
}
}
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
self.elapsedTimeInSecond -= 1
self.updateTimeLabel()
})
}
func resetTimer(second:Int) {
timer?.invalidate()
elapsedTimeInSecond = second
updateTimeLabel()
}
func updateTimeLabel() {
let seconds = elapsedTimeInSecond % 60
let minutes = (elapsedTimeInSecond/60) % 60
mySecondLabel.isHidden = false
mySecondLabel.text = String(format: "%02d:%02d", minutes,seconds)
}
}
extension TableViewCell:AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(Id)/Record/")
let fileName = message?.content.substring(from: 62)
let fileURL = documentsDirectoryURL.appendingPathComponent(fileName!)
if FileManager.default.fileExists(atPath: fileURL.path) {
let asset = AVURLAsset(url: URL(fileURLWithPath: fileURL.path), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
DispatchQueue.main.async {
self.resetTimer(second: Int(audioDurationSeconds))
self.myRecordPlayerBtn.imageView!.stopAnimating()
self.myRecordPlayerBtn.imageView?.image = #imageLiteral(resourceName: "img_myRocordDefault")
}
}
}
}
Probably first initialize to check if your player is playing
if audioPlayer != nil{
if audioPlayer?.isPlaying == true {
audioPlayer?.stop()
DispatchQueue.main.async {
self.resetTimer(second: self.elapsedTimeInSecond)
self.startTimer()
}
}
}
If you don't want to play two audio track at the same time, you should use a shared instance of AVAudioPlayer
It will be better for performances and you can define the instance as static var in your controller. It will be accessible in each cell.
I have developed a music palyer application, and I used a shared instance in the MusicPlayManager:
class MusicPlayManager{
var player : AVAudioPlayer?
static let sharedInstance = MusicPlayManager.init()
private override init() {
super.init()
}
// something else, such as palyNext, playPrevious methods
}
In your viewController,you can use MusicPlayManager.sharedInstance.player

Swift: Read pdf file into pdf application reader

How can I display all applications that can read pdf file (adobe pdf reader for example) when a button is clicked? I searched but I found that the majority use UIWebView to display pdf file. How can I do it with the way that I described?
Edit:
I have only the pdf link that I get from the server
Try this
var docController:UIDocumentInteractionController!
let pdfUrl = NSURL(string: "ENTER_URL_OF_PDF")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
downloadDoc(pdfUrl: pdfUrl!)
}
#IBAction func buttonAction(_ sender: AnyObject) {
docController.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true)
}
func downloadDoc(pdfUrl : NSURL) {
let urlTest = self.pdfUrl!.absoluteString
let pdfUrl = NSURL(string: urlTest!)
if(pdfUrl != nil){
let pdfRequest: NSURLRequest = NSURLRequest(url: pdfUrl! as URL)
NSURLConnection.sendAsynchronousRequest(pdfRequest as URLRequest, queue: OperationQueue.main) {(response, data, error) in
let httpResponse = response as? HTTPURLResponse
if(httpResponse?.statusCode == 200 && error == nil){
let documentsUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first as! NSURL
if let fileName = self.pdfUrl!.lastPathComponent {
let destinationUrl = documentsUrl.appendingPathComponent(fileName)
if let data = data {
do {
try data.write(to: destinationUrl!, options: .atomic)
} catch {
print(error)
}
self.docController = UIDocumentInteractionController(url: destinationUrl!)
}
}
}
}
}
}
You can go with UIDocumentInteractionController, it will handle all for you like zooming pdf, scrolling, showing suitable app to handle the pdf.
SWIFT 2.3:
import UIKit
class ViewController:UIViewController, UIDocumentInteractionControllerDelegate {
var documentController: UIDocumentInteractionController = UIDocumentInteractionController()
override func viewDidLoad() {
super.viewDidLoad()
downloadFileForfileObject("https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func downloadFileForfileObject(url: String) { //Download pdf File asynchronosly
let documentURL = NSURL(string: url)
let documentsURLPath = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
let fileExtension = ((documentURL!.pathComponents)?.last)! as String
let request: NSURLRequest = NSURLRequest(URL: documentURL!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60)
let fileURLPath = documentsURLPath.URLByAppendingPathComponent("\(fileExtension)")
let sessionCobfig = NSURLSessionConfiguration()
let session = NSURLSession(configuration: sessionCobfig, delegate: nil, delegateQueue: nil)
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error == nil {
self.openSelectedDocumentFromURL((fileURLPath?.path!)!)
} else {
print(error?.localizedDescription)
}
}
task.resume()
}
func openSelectedDocumentFromURL(documentURLString: String) {
let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString)
documentController = UIDocumentInteractionController(URL: documentURL)
documentController.delegate = self
documentController.presentPreviewAnimated(true)
}
// MARK: - UIDocumentInteractionViewController delegate methods
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
Call downloadFileForfileObject() in viewDidLoad method with your pdf url as a parameter. The pdf will be automatically shown by UIDocumentInteractionController delegate method.
SWIFT 3:
import UIKit
class MOViewController:UIViewController, UIDocumentInteractionControllerDelegate {
var documentController: UIDocumentInteractionController = UIDocumentInteractionController()
override func viewDidLoad() {
super.viewDidLoad()
downloadFileForfileObject(url: "https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func downloadFileForfileObject(url: String) { //Download pdf File asynchronosly
let documentURL = NSURL(string: url)
let documentsURLPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
let fileExtension = ((documentURL!.pathComponents)?.last)! as String
let request: URLRequest = URLRequest(url: documentURL! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 60)
let fileURLPath = documentsURLPath.appendingPathComponent("\(fileExtension)")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let teask = session.dataTask(with: request) { (data, response, error) in
if (error == nil) {
// Success
self.openSelectedDocumentFromURL(documentURLString: fileURLPath!.path)
} else {
print(error?.localizedDescription)
}
}
teask.resume()
}
func openSelectedDocumentFromURL(documentURLString: String) {
let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString)
documentController = UIDocumentInteractionController(url: documentURL as URL)
documentController.delegate = self
documentController.presentPreview(animated: true)
}
// MARK: - UIDocumentInteractionViewController delegate methods
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
Document download verification:
You check whether document is downloading or not by follows, see image.
Output:
Thanks:)

ios swift play video uploaded from cloudkit

I am trying to play a video downloaded from cloudkit. I use the same query method that I use for downloading image:
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
for cafe in results! {
let newCafe = Cafe()
newCafe.address = cafe["address"] as? String
newCafe.name = cafe["name"] as? String
newCafe.email = cafe["email"] as? String
newCafe.description = cafe["description"] as? String
newCafe.location = cafe["location"] as? CLLocation
newCafe.cafeImage = cafe["cafeImage"] as? CKAsset
newCafe.offer_wifi = cafe["offer_wifi"] as? Bool
newCafe.smoking_area = cafe["smoking_area"] as? Bool
newCafe.cafeVideo = cafe["video"] as? CKAsset // <== I want to use this
self.cafes.append(newCafe)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(self.cafes.count, forKey: "PreviousCafeCount")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
Spinner.sharedLoader.hideLoading()
})
inside the cafeDetailViewController, I create a button that trigger playing a video using AVPlayer. AVKit and AVFoundation are already imported.
#IBAction func playVideo(sender: AnyObject) {
if let file = cafeDetail.cafeVideo {
let player = AVPlayer(URL: file.fileURL)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
}
}
However the result is this:
follow up question: how can I implement model association in swift? Similar to has_many and belongs_to association in rails. I don't think downloading the whole video beforehand is a good solution.
From what I can see, you need to save the video to a local file and then play that file. This is modified from something I wrote to mess around with CloudKit.
import UIKit
import CloudKit
import AVKit
import AVFoundation
class CloudKitTestViewController: UIViewController {
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
var videoURL: NSURL!
#IBAction func load(sender: AnyObject) {
let predicate = NSPredicate(format: "videoName = %#", "nameOfVideoGoesHere")
activityIndicator.startAnimating()
let query = CKQuery(recordType: "Videos", predicate: predicate)
publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) in
if error != nil {
dispatch_async(dispatch_get_main_queue()) {
self.notifyUser("Cloud Access Error",
message: error!.localizedDescription)
}
} else {
if results!.count > 0 {
let record = results![0]
dispatch_async(dispatch_get_main_queue()) {
!)
let video = record.objectForKey("videoVideo") as! CKAsset
self.videoURL = video.fileURL
let videoData = NSData(contentsOfURL: self.videoURL!)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let destinationPath = NSURL(fileURLWithPath: documentsPath).URLByAppendingPathComponent("filename.mov", isDirectory: false)
NSFileManager.defaultManager().createFileAtPath(destinationPath.path!, contents:videoData, attributes:nil)
self.videoURL = destinationPath
print(self.videoURL)
}
} else {
dispatch_async(dispatch_get_main_queue()) {
self.notifyUser("No Match Found",
message: "No record matching the address was found")
}
}
}
dispatch_async(dispatch_get_main_queue(), {
self.activityIndicator.stopAnimating()
})
}
}
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?) {
let destination = segue.destinationViewController as!
AVPlayerViewController
let url = videoURL
print(videoURL)
destination.player = AVPlayer(URL: url!)
}
}

NSFileManager.defaultManager().createFileAtPath() returning false

After like a thousand print() statements, I have finally pinpointed the problem! However, I'm not sure how to fix it. The problem lies in the line:
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
According to the Apple Developer's guide, this line of code returns true if the operation was successful or if the item already exists, otherwise false.
This line is returning a false and I'm not exactly sure why because the code preceding the line seems to be okay. Anybody have any suggestions on how to solve this bug?
The rest of the code is here:
//
// ViewController.swift
// Downloading An Image From The Web
//
// Created by Jae Hyun Kim on 9/6/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")
let urlRequest = NSURLRequest(URL: url!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
}
else {
if let bach = UIImage(data: data!) {
//self.image.image = bach
let documentsDirectory:String?
let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.PicturesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
print(paths)
if paths.count > 0 {
documentsDirectory = paths[0] as? String
let savePath = documentsDirectory! + "/bach.jpg"
print(NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil))
if NSFileManager.defaultManager().fileExistsAtPath(savePath) {
print("file available")
}
else {
print("file not available")
}
self.image.image = UIImage(contentsOfFile: savePath)
}
}
}
})
task!.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")!
let urlRequest = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
// you should always do it from the main queue otherwise you will experience a big delay when trying to display your image
dispatch_async(dispatch_get_main_queue()) {
// unwrap your data
if let data = data {
print(data.length)
// get your caches directory URL
let cachesDirectory = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// create your local file url by appending your url last path component
let fileUrl = cachesDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
// save downloaded data to disk
if data.writeToURL(fileUrl, atomically: true) {
print(true)
// load your saved image from disk
self.image.image = UIImage(contentsOfFile: fileUrl.path!)
}
}
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Note you will need to edit your plist as follow:

Json : Save Images into CoreData in Swift

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!

Resources