upload excel using alamofire - ios

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

Related

WebView returning empty after file exported successfully

Working on webView and exported pdf functionality working fine.All functionality regarding export PDF in separate extension WKWebView.When exportPDf downloading complete sending events to javascript but webview returning nill.Calling the object of homeController in WKWebView extension for passing the parameter url in exportPDFUrl method.In HomeViewController there is a method callJavaScript where webview returning nill and go to else block.
extension WKWebView {
func saveWebViewPdf(data: NSMutableData) -> String {
var homeVC = HomeViewController()
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("\(UUID().uuidString).pdf")
if data.write(to: pdfPath, atomically: true) {
return homeVC.exportPDFUrl(pdfPath.path)
} else {
return ""
}
}
}
class HomeViewController {
// MARK: - Export PDF Download Completed EVENTS
func exportPDFUrl(_ url: String) -> String {
return "\(exportPDFDownload(url))"
}
func exportPDFDownload(_ url: String) {
callJavaScript(script: makeJSForExportPDFDownload(url))
}
func makeJSForExportPDFDownload(_ url: String) -> String {
return "window.dispatchEvent(new CustomEvent('pdfDownloadComplete',{detail:'\(url)'}))"
}
func callJavaScript(script: String) {
DispatchQueue.main.async { [weak self] in
guard let self = self else {print("something wrong"); return}
self.webview!.evaluateJavaScript(script) { (result, error) in
if error == nil {
print(result as Any)
}
}
}
}
}

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?

Thread 1: EXC_BAD_ACCESS (code=2, address=..) using Macaw Pod iOS Swift?

I'm using Macaw to parse and render an SVG file gotten from the server.
Here's the source code: https://pastebin.com/g9vUCpGX
How can I accomplish this task?
class ViewController: UIViewController{
#IBOutlet weak var profileBadge: SVGView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/couchdb.svg")!
if profileBadge != nil{
profileBadge.loadSVG(from: url)
}
}
}
extension SVGView {
func loadSVG(from url: URL) {
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: url) else {
return
}
guard let svgString = String(data: data, encoding: .utf8) else {
return
}
let node = (try? SVGParser.parse(text: svgString)) ?? Group()
DispatchQueue.main.async {
print(node)
self.node = node
}
}
}
}
You may use XIB or Storyboard.. It works using like below.
import UIKit
import Macaw
import SnapKit
class ViewController: UIViewController{
var profileBadge: SVGView = SVGView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(profileBadge)
profileBadge.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
let url = URL(string: "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/couchdb.svg")!
if profileBadge != nil{
profileBadge.loadSVG(from: url)
}
}
}
extension SVGView {
func loadSVG(from url: URL) {
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: url) else {
return
}
guard let svgString = String(data: data, encoding: .utf8) else {
return
}
let node = (try? SVGParser.parse(text: svgString)) ?? Group()
DispatchQueue.main.async {
print(node)
self.node = node
}
}
}
}
Was able to figure out the issue. :) profileBadge should've been a UIView not UIImageView. And in the Identity Inspector, Class should've been SVGView and Module should've been Macaw.

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:

Array of multiple URL's NSFileManager Swift

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

Resources