NSFileManager.defaultManager().createFileAtPath() returning false - ios

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:

Related

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))
}
}
}

Object ***********/******.jpg doesn't exist, Firebase Storage

My problem is when I run the application, this error appears in the console
Optional ("Users Profile / Kk1kKMF89BH778vgd788ju7.jpg does not exist.")
But the file exists in my Firebase storage. I try to download the image to a UIImage named phSelfie.
This is my code:
import UIKit
import Firebase
class SeeSelfieViewController: UIViewController {
var storage = FIRStorage.storage()
#IBOutlet var phSelfie: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let gsRef = storage.reference(forURL: "gs://******-****.appspot.com/profileUsers/")
let user = FIRAuth.auth()!.currentUser!
let imageRef = gsRef.child("\(user.uid).jpg")
imageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
if error != nil {
print("\(error?.localizedDescription)") <------ This run the error!!
} else {
let imageSelfie = UIImage(data: data!)
self.phSelfie.image = imageSelfie
print("Succes")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I see a few issues:
storage.reference(forURL: "gs://******-****.appspot.com/profileUsers/") should be an HTTP URL, or you should just use storage.reference().child("profileUsers")
Users Profile / Kk1kKMF89BH778vgd788ju7.jpg seems to have spaces in the object, which would be percent escaped %20 in the actual object name.
Users Profile seems to not match profileUsers, which is what the object name above says...
// Press Upload Button Action
#IBAction func uploadButton(_ sender: Any) {
print("Upload Button pressed")
// Create a root reference
let storage = Storage.storage()
let storageReferance = storage.reference()
let mediaFolder = storageReferance.child("media")
print("Media Folder Created")
if let data = UIImageView.image?.jpegData(compressionQuality: 0.5) {
print("Image Selected")
let imageReference = mediaFolder.child("image.jpg")
imageReference.putData(data, metadata: nil) { (metadata,error) in
if error != nil {
print(error?.localizedDescription)
print("Image selection error")
}else{
imageReference.downloadURL { url, error in
if error == nil{
let imageURL = url?.absoluteString
print("Image selection SUCCESS")
print(imageURL)
}
}
}
}
}
}

Swift image from URL not showing

I'm new to swift and not sure why an image is loading from the url.
The code:
let url = NSURL(string: imageURL)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
println("Should load the pic!")
var profilePic = UIImage(data: data)
self.profileImage.setImage(profilePic)
})
In my interface controller I have an image called "profileImage" that is linked with an IBOutlet. One thing I noticed is that "Should load the pic!" does not appear in the console so it is not getting to the setImage code..
when you downloading image from URL. I suggest you to do this in background. here is the example code for you:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var profileImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
profileImage.contentMode = UIViewContentMode.ScaleAspectFit
if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
downloadImage(checkedUrl)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in
completion(data: NSData(data: data))
}.resume()
}
func downloadImage(url:NSURL){
println("Started downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
getDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
println("Finished downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
self.profileImage.image = UIImage(data: data!)
}
}
}
}
Try this, as it may help you:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var profilePic = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://devhumor.com/wp-content/uploads/2012/04/devhumor.com_pointers.png")));
self.profileImage.setImage(profilePic);
});

Runtime error in Swift...NSData is Nill (when it shouldn't be)

I am getting a runtime error in Swift...I have a very simple program below. I am getting data = nil when there should be data there. Scratching my head here...
The specific error is "fatal error: unexpectedly found nil while unwrapping an Optional value"
//
// ViewController.swift
// TestingImageLoad
//
// Created by Daniel Riaz on 2/21/15.
// Copyright (c) 2015 Daniel Riaz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var testImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
loadImage()
// Do any additional setup after loading the view, typically from a nib.
}
func loadImage() {
var url: String = "http://imgur.com/jn4z6wpl.jpeg"
let testURL: NSURL = NSURL(fileURLWithPath: url)!
let data: NSData = NSData(contentsOfURL: testURL)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//URL that works to use http://imgur.com/jn4z6wpl.jpeg
// var postURL: NSURL = NSURL(string: self.detailPost!.url)!
// var data: NSData = NSData(contentsOfURL: postURL)!
// var imageToShare = UIImage(data: data)!
}
You don't want fileURLWithPath: - that is for access to files on the local file system. You just want NSURL(string:) -
This worked for me in a Playground -
func loadImage() {
var url: String = "http://imgur.com/jn4z6wpl.jpeg"
let testURL = NSURL(string:url)
if (testURL != nil) {
let data = NSData(contentsOfURL: testURL!)
}
}

Playing Audio File from the directory in swift

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.
}
}

Resources