Array of multiple URL's NSFileManager Swift - ios

How would I go about adding multiple URL's? I wonder how I can set that up into an array with swift.
if let audioUrl = NSURL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
println("LOADING AUDIO")
if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
println("AUDIO LOADED")
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let destinationUrl = documentsUrl.URLByAppendingPathComponent(audioUrl.lastPathComponent!)
println(destinationUrl)
if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
println("The file already exists at path")
} else {
if myAudioDataFromUrl.writeToURL(destinationUrl, atomically: true) {
println("file saved")
} else {
println("error saving file")
}
}
}
}

In this case I think you should use NSURLSession.sharedSession().dataTaskWithURL to do multiple downloads from your links but keeping the download operation asynchronous. You need to add a callback block to it. You should do as follow:
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
let musicArray:[String] = ["http://freetone.org/ring/stan/iPhone_5-Alarm.mp3","http://freetone.org/ring/stan2/Samsung_Galaxy_S4-SMS.mp3","https://www.sounddogs.com/sound-effects/25/mp3/235178_SOUNDDOGS__al.mp3"]
var musicUrls:[NSURL!]!
// create a function to start the audio data download
func getAudioDataFromUrl(audioUrl:NSURL, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(audioUrl) { (data, response, error) in
completion(data: data)
}.resume()
}
// create another function to save the audio data
func saveAudioData(audio:NSData, destination:NSURL) -> Bool {
if audio.writeToURL(destination, atomically: true) {
println("The file \"\(destination.lastPathComponent!.stringByDeletingPathExtension)\" was successfully saved.")
return true
}
return false
}
// just convert your links to Urls
func linksToUrls(){
musicUrls = musicArray
.map() { NSURL(string: $0) }
.filter() { $0 != nil }
}
// create a loop to start downloading your urls
func startDownloadingUrls(){
for url in musicUrls {
let destinationUrl = documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!)
if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
println("The file \"\(destinationUrl.lastPathComponent!.stringByDeletingPathExtension)\" already exists at path.")
} else {
println("Started downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
getAudioDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
println("Finished downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
println("Started saving \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
if self.saveAudioData(data!, destination: self.documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!) ) {
// do what ever if writeToURL was successful
} else {
println("The File \"\(url.lastPathComponent!.stringByDeletingPathExtension)\" was not saved.")
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println("Begin of code")
linksToUrls()
startDownloadingUrls()
println("End of code")
}

Related

share extension loading a WhatsApp Zip attachment is not working

I am trying to read Export chat Zip file but share extension loading a WhatsApp Zip attachment is not working.
I am using this code -:
override func viewDidLoad() {
super.viewDidLoad()
getURL()
}
private func getURL() {
let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
let itemProvider = extensionItem.attachments?.first
let zip_type = String(UTType.zip.identifier)
if itemProvider!.hasItemConformingToTypeIdentifier(zip_type) {
itemProvider!.loadItem(forTypeIdentifier: zip_type, options: nil, completionHandler: { (item, error) -> Void in
guard let url = item as? NSURL else { return }
OperationQueue.main.addOperation {
print("url\(url)")
self.path = url as URL
do {
let unzipDirectory = try Zip.quickUnzipFile(self.path)
print("unzipDirectory\(unzipDirectory)")
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(unzipDirectory.lastPathComponent)
print("fileURL\(fileURL)")
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
print(text2)
}
catch {/* error handling here */}
}
}
catch {
print("Something went wrong")
}
}
})
} else {
print("error")
}
}
override func isContentValid() -> Bool {
print("Hiii")
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
override func didSelectPost() {
print("hello")
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return []
}
in console error is:
[core] SLComposeServiceViewController got attachment coarseType 0
[core] SLComposeServiceViewController made no attachment for itemProvider conforming to public.file-url
Can anyone help please?

How to add image to QuickLook that is stored in variable

I would like to add a couple of images that are stored in variables to a QLPreviewController. The QuickLook datasource requires a fileURL which I'm not sure how to get for an image that is stored in a variable and not in disk or in the project.
Any pointers as to how I can solve this issue?
Below code can be used to to display image file from local and from URL in QLPreviewController.
import UIKit
import QuickLook
class ViewController: UIViewController {
lazy var previewItem = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func displayLocalFile(_ sender: UIButton){
let previewController = QLPreviewController()
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "bull.png")
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
#IBAction func displayFileFromUrl(_ sender: UIButton){
// Download file
self.downloadfile(completion: {(success, fileLocationURL) in
if success {
// Set the preview item to display======
self.previewItem = fileLocationURL! as NSURL
// Display file
DispatchQueue.main.async {
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
}else{
debugPrint("File can't be downloaded")
}
})
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle.main.path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func downloadfile(completion: #escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: "https://developer.apple.com/wwdc20/images/hero/memoji/large/L7_2x.jpg")
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("filename.jpg")
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
debugPrint("The file already exists at path")
completion(true, destinationUrl)
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
print("File moved to documents folder")
completion(true, destinationUrl)
} catch let error as NSError {
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
}
//MARK:- QLPreviewController Datasource
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}

Saved data on JSON file but can not retrieve previous data, only new entries

I am saving datas on on the json file on the first VC , load the data as well and display it when switching tab. When I kill the app or re run the app again, add new datas to the JSON file, only those new datas are on the JSON file, previous datas are gone(deleted without deleting them manually) and can not be load. How do I save the file so that next time I run the program it will just append to the previous data ?
class ViewController: UIViewController {
var game : Game?
var weekLeague : [[Game]]? = []
override func viewDidLoad() {
super.viewDidLoad()
creation()
}
#IBAction func endWLButton(_ sender: UIButton) {
if games != nil {
weekLeague?.append(games!)
}
save()
}
func save(){
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("ArrayOfArray.json")
print(fileUrl)
let json = try? JSONEncoder().encode(weekLeague)
do {
try json?.write(to: fileUrl)
print(json!)
print(weekLeague)
print("JSON data was written to teh file successfully!")
}catch{
print(error)
}
}
func ShouldSendGame(game: Game) {
self.game = game
games?.append(game)
}
func creation(){
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("ArrayOfArray.json")
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
// creating a .json file in the Documents folder
if !fileManager.fileExists(atPath: jsonFilePath!.path, isDirectory: &isDirectory) {
let created = fileManager.createFile(atPath: jsonFilePath!.path, contents: nil, attributes: nil)
if created {
print("File created ")
} else {
print("Couldn't create file for some reason")
}
} else {
print("File already exists")
}
}
}
class AllLeagueController : UITableViewController {
var arrayOfArrayGamesCopy : [[Game]] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.global().async {
self.loadData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func loadData() {
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("ArrayOfArray.json")
do{
let data = try Data(contentsOf:fileUrl)
let decoder = JSONDecoder()
let jsonData = try decoder.decode([[Game]].self, from: data)
arrayOfArrayGamesCopy = jsonData
print("Succes")
print(jsonData.count)
} catch{
print(error)
}
}
}
You need to load data here before save ... Also you need to have separate class for saving and loading data .. dot do that in controller .. its against Single Responsibility Principle ...Your load function should return array of [Game] and save data should return success or failure
#IBAction func endWLButton(_ sender: UIButton) {
//load and set data in games from file ...then append current data and save to file
if games != nil {
weekLeague?.append(games!)
}
save()
}

How to download multiple audio files from url and play offline in App

I want to download multiple audio files from url and play offline in App . This is what i do in my coding but some time array loop stop downloading . And Also I have one more array to download. and this code is only for download. playing audio is working proper.
override func viewDidLoad() {
super.viewDidLoad()
print("Begin of code")
self.linksToUrls()
self.startDownloadingUrls()
print("End of code")
}
// create a function to start the audio data download
func getAudioDataFromUrl(audioUrl:NSURL, completion: #escaping ((_ data: NSData?) -> Void)) {
URLSession.shared.dataTask(with: audioUrl as URL) { (data, response, error) in
completion(data as NSData?)
print("dfdgfdg",data!)
}.resume()
}
// create another function to save the audio data
func saveAudioData(audio:NSData, destination:NSURL) -> Bool {
if audio.write(to: destination as URL, atomically: true) {
print("The file \"\(destination.lastPathComponent!)\" was successfully saved.")
return true
}
return false
}
// just convert your links to Urls
func linksToUrls(){
print("IntroductoryMusicFile1 = count = ",IntroductoryMusicFile1.count)
audioUrls = NewsAudio1
.map() { NSURL(string: $0) }
.filter() { $0 != nil }
print("introcount",IntroductoryMusicFile1.count)
musicUrls = IntroductoryMusicFile1
.map() { NSURL(string: $0) }
.filter() { $0 != nil }
}
// create a loop to start downloading your urls
func startDownloadingUrls(){
arrayplay.removeAll()
//if (musicUrls = "The URL?"){ }
// let syn = SyncBlock()
for url in 0 ... musicUrls.count-1 {
let aaa = musicUrls[url]
let audioType = audioUrls[url]
print(aaa!)
print("audioType",audioType!)
if aaa == NSURL(string: ""){
arrayplay.append("")
}else{
print("Started downloading \"\(String(describing: aaa?.lastPathComponent!))\".")
let url1 = aaa
let request = URLRequest(url: url1! as URL)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
if httpResponse.statusCode == 404{
print("Refresh token...")
// self.audioPlay()
self.arrayplay.append("")
}else{
self.getAudioDataFromUrl(audioUrl: aaa!) { data in
DispatchQueue.main.async() {
print("Finished downloading \"\(String(describing: aaa?.lastPathComponent!))\".")
print("Started saving \"\(String(describing: aaa?.lastPathComponent!))\".")
if self.saveAudioData(audio: data!, destination: self.documentsUrl.appendingPathComponent(aaa!.lastPathComponent!)! as NSURL ) {
// do what ever if writeToURL was successful
// print("",data)
self.arrayplay.append(aaa!.lastPathComponent!)
self.data1 = self.arrayplay as! [String]
print("data1",self.data1)
print("",self.data1.count)
if self.data1.count == self.musicUrls.count {
print("complete")
self.downloadDataAnnotation()
}
//self.synk.complete()
// print("abc")
} else {
// print("The File \"\(url.lastPathComponent!.stringByDeletingPathExtension)\" was not saved.")
}
}
}
}
}
}
task.resume()
}
}
}
Can any one suggest me the better code or any other way to download multiple audio file ...

upload excel using alamofire

i try to upload an excel file using alamofire in iOS. my file path is
file:///Users/macbook/Library/Developer/CoreSimulator/Devices/75477755-3367-41DE-B3D2-A2E22C7AE069/data/Containers/Data/Application/45CB65D0-0B7C-4F17-89AA-2163301F2E6B/Documents/appImportContacts.xls
and the code I use
// import Alamofire
func uploadWithAlamofire(filePath : String ) {
let url = URL(fileURLWithPath: filePath)//"/foo/bar/file.text")
let dirUrl = url.deletingLastPathComponent()
print(dirUrl.path)
// Output: /foo/bar
let fileURL = Bundle.main.url(forResource: "appImportContacts", withExtension: "xls", subdirectory: dirUrl.path)
Alamofire.upload(fileURL!, to: "http://192.168.1.213/api/app/UploadExcelFile").responseJSON { response in
debugPrint(response)
}
I get fileURL nil
How can I make my file path as Bundle to pass to alamofire?
Alamofire version:4
Xcode version:8.2.1
Swift version:3
Platform(s) running Alamofire:iOS
macOS version running Xcode:10
I found the solution
//
// HowToDownloadViewController.swift
// WhiteSms
//
// Created by MacBook on 7/26/1396 AP.
// Copyright © 1396 AP IPE. All rights reserved.
//
import UIKit
import FileExplorer
import Alamofire
import HandyJSON
import SwiftyJSON
class ImportExcelViewController: UIViewController, FileExplorerViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func onDownload_Click(_ sender: Any) {
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("appImportContacts.xls")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://192.168.1.213/downloads/appImportContacts.xls")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task.resume()
}
#IBAction func onUpload_Click(_ sender: Any) {
let fileExplorer = FileExplorerViewController()
fileExplorer.canRemoveFiles = true //specify whether user is allowed to remove files
fileExplorer.canRemoveDirectories = false //specify whether user is allowed to remove directories
fileExplorer.delegate = self
self.present(fileExplorer, animated: true, completion: nil)
}
public func fileExplorerViewControllerDidFinish(_ controller: FileExplorerViewController) {
}
public func fileExplorerViewController(_ controller: FileExplorerViewController, didChooseURLs urls: [URL]) {
//Your code here
print(urls)
var fileAddress = urls[0]
uploadWithAlamofire(filePath: urls[0].absoluteString)
}
// import Alamofire
func uploadWithAlamofire(filePath : String ) {
let url = URL(fileURLWithPath: filePath)//"/foo/bar/file.text")
let dirUrl = url.deletingLastPathComponent()
print(dirUrl.path+"/appImportContacts.xls")
// Output: /foo/bar
let filePath = dirUrl.path+"/appImportContacts.xls"
var bytes = [UInt8]()
if let data = NSData(contentsOfFile: filePath) {
var buffer = [UInt8](repeating: 0, count: data.length)
data.getBytes(&buffer, length: data.length)
bytes = buffer
}
Alamofire.upload(multipartFormData: {
multipartFormData in
multipartFormData.append(Data(fromArray: bytes), withName: "appImportContacts",fileName: "appImportContacts.xls", mimeType: "application/octet-stream")
},
to:"http://192.168.1.213/api/app/UploadExcelFile")
{
(result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
}
extension Data {
init<T>(fromArray values: [T]) {
var values = values
self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))
}
func toArray<T>(type: T.Type) -> [T] {
return self.withUnsafeBytes {
[T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
}
}
}

Resources