search file from document directory in ios - xcode

I have enabled itune file sharing in my Application.
I have added pdf file in my application directory.
now I want to search that file using my app. and upload it on server.
also if there multiple file and folder I want to show in application. search folder and select specific file and upload it. please suggest best way for doing that.
Appriciate for help.

do
{
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
print(dirPaths)
let Pnames = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPaths) as [String]
var ProductImgs:Array<String> = Array<String>()
var ProductNames:Array<String> = Array<String>()
for name in Pnames
{
let fileName:String = name
if fileName.hasSuffix(".pdf")
{
PdfURLs.append(dirPaths.stringByAppendingString("/\(fileName)"))
PdfNames.append(fileName)
print(dirPaths.stringByAppendingString("/\(fileName)"))
}
}
}
catch
{
print(error)
}

If you are fine using third party libraries, it would be great to use Alamofire. It is an HTTP networking library written in Swift.
You can upload the file easily using this one,
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
For a complete understanding of this library check out this link, https://github.com/Alamofire/Alamofire

Related

NativeScript: How to copy a file from an apps folder to a user accessible folder?

I want to copy storage.db to documents or downloads folder. It's very easy to get the file path:
const filePath = application.android.context.getDatabasePath("storage.db").getAbsolutePath();
But, what isn't that easy is to copy that file to a folder users have access to. I searched this whole forum, and I found nothing useful for my case.
I'm using NativeScript 4.0.1 with vanilla JS.
If you want to share the DB file, the easiest way is to use nativescript-share-file plugin, send the file path and it will give you a nice dialog with intent picker, user may choose to Email the file Or save it to local folder etc.,
const shareFile = new ShareFile();
shareFile.open({
path: filePath,
});
I finally found the solution. I've seen so many users trying to achieve this, and I hope this will help all of you.
Add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Install nativescript-permissions:
npm i nativescript-permissions
Asking for permission:
const permissions = require('nativescript-permissions');
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, "");
Require the necessary modules:
const fileSystemModule = require("tns-core-modules/file-system");
const application = require("application");
Then, create this function where you need to use it:
function copyFile() {
var myInput = new java.io.FileInputStream(appModule.android.context.getDatabasePath("storage.db").getAbsolutePath());
var myOutput = new java.io.FileOutputStream("/storage/emulated/0/databases/storage.db");
try {
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), 1024);
var length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
}
catch (err) {
console.info("Error", err);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
exports.copyFile = copyFile;
In my case, the file storage.db will be copied to /storage/emulated/0/databases. If you need to create a folder, just do the following:
try {
var javaFile = new java.io.File("/storage/emulated/0/newfolder");
if (!javaFile.exists()) {
javaFile.mkdirs();
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
catch (err) {
console.info("Error", err);
}
If the destination folder has a file with the same name as the one you want to copy, you need to remove it first. That's why you should create a specific folder to guarantee it's empty.

You don't have permission to save file in Mac Mojave

In my macOS app I'm trying to create a directory using the below extension
extension URL {
static func createFolder(folderName: String, folderPath:URL) -> URL? {
let fileManager = FileManager.default
let folderURL = folderPath.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path) {
do {
// Attempt to create folder
// try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
// try fileManager.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
try fileManager.createDirectory(atPath: folderURL.relativePath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription + ":\(folderURL.path)")
return nil
}
}
return folderURL
}
}
When I invoke this call its giving me error
You don’t have permission to save the file “FolderName” in the folder
“SelectedFolder”.:/Users/USERNAME/Workspace/SelectedFolder/FolderName
I have taken look at a similar post and have tried all methods but its still giving me the error, am I missing something here? Any help is appreciated
I am Assuming that your app is sandboxed. So you don't have permission to write folder for location where you are trying to.
If it not intended for Sandboxed you can disable the App Sandbox, it can be turned off by clicking on your project file > target name, selecting the capabilities tab and switching the App Sandbox off.
File System Programming Guide: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
App Sandbox documentation here: https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html
You can also look security scoped bookmark for persistent resource access.
Documentation here:
https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16
https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW18

Unexpected response from NSFileManager in Sketch Plugin

I published a Sketch Plugin with some functionalities with a strong dependency in files management.
When execute, plugin needs to check if a folder exists, if not, create, and then manage several files inside this directory.
Some weeks ago, one user reported plugin was crashing in a new Sketch version.
Unexpected response from:
fileExistsAtPath return -folder does not exist- when actually exists in that path
createDirectoryAtPath return 'error' when trying to create a non-existing folder (I've tested both when folder exists and not)
Quick example:
Request
var document = context.document
var documentName = document.displayName()
var documentFolderPath = decodeURIComponent(document.fileURL()).replace('file:///','').replace(documentName,"")
print(documentName)
print(documentFolderPath)
var translationsFolderName = documentName.replace('.sketch','_translations')
var translationsFolderPath = documentFolderPath+translationsFolderName+'/'
print(translationsFolderName)
print(translationsFolderPath)
var fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:translationsFolderPath isDirectory:'YES'])
{
print(translationsFolderPath+" folder does not exist")
if(![fileManager createDirectoryAtPath:translationsFolderPath withIntermediateDirectories:'YES' attributes:nil error:nil])
{
print(translationsFolderPath+" folder can't be created")
}
}
Response
test.sketch
Users/myuser/Documents/
test_translations
Users/myuser/Documents/test_translations/
Users/myuser/Documents/test_translations/ folder does not exist
Users/myuser/Documents/test_translations/ folder can't be created
Script executed in 0.034733s
Any idea?
Thanks!
Your file path is not rooted (doesn't start with /)

Nativescript: iOS Utils openFile

I am working on code to open files which have been downloaded from the app, and I am using the utils.ios.openFile function. I can get the files to display on screen, however I am also getting the following warning on the console. Has anyone run into this, or have any ideas on how to resolve?
Unbalanced calls to begin/end appearance transitions for
. Cannot find
preview item for proxy: -
mobile-application.png (0)
The following is the code I am using:
var documents = fs.knownFolders.documents();
filePath = fs.path.join(documents.path, filename);
if(fs.File.exists(filePath)){
utilModule.ios.openFile(filePath)
.catch(function(error){
});
} else {
return Promise.reject(new Error("File not Found"));
}
You could set the filePath to the image, without using openFile(filePath) method. You could review the below-attached example.
let folder = fs.knownFolders.documents();
let path = fs.path.join(folder.path, "Test.png");
if(fs.File.exists(path )){
image.src=path
}

Swift : Share text through Twitter

So basically I am making an event app. Everything has been going smoothly but there's just sharing the event to twitter.
I have searched the internet but all I am getting is using the native app of twitter which I don't want. I want to use the browser to tweet.
I have implemented this method for FB sharing.
Any idea would help me a lot.
let content = FBSDKShareLinkContent()
content.contentURL=NSURL(string: "http://facebook.com")
content.imageURL = NSURL(string: "http://facebook.com")
content.contentTitle = "Shou 3emlin test app "
content.contentDescription = "testing testing testing"
let shareDialog = FBSDKShareDialog()
shareDialog.fromViewController = self
shareDialog.mode=FBSDKShareDialogMode.Browser
shareDialog.shareContent = content
if !shareDialog.canShow() {
shareDialog.mode=FBSDKShareDialogMode.Native
shareDialog.shareContent = content
}
if shareDialog.canShow() {
shareDialog.show()
}
Put this in an action method of a button or in the method where you want to use the browser to tweet your text Swift 3.0:
let tweetText = "your text"
let tweetUrl = "http://stackoverflow.com/"
let shareString = "https://twitter.com/intent/tweet?text=\(tweetText)&url=\(tweetUrl)"
// encode a space to %20 for example
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
// cast to an url
let url = URL(string: escapedShareString)
// open in safari
UIApplication.shared.openURL(url!)
Result:
Take a look at Fabric.io. This SDK allows you to compose tweets directly from your app.
let composer = TWTRComposer()
composer.setText("just setting up my Fabric")
composer.setImage(UIImage(named: "fabric"))
// Called from a UIViewController
composer.showFromViewController(self) { result in
if (result == TWTRComposerResult.Cancelled) {
print("Tweet composition cancelled")
}
else {
print("Sending tweet!")
}
}
let tweetText = "hy"
let tweetUrl = "http://rimmi/"
let shareString = "https://twitter.com/intent/tweet?text=\(tweetText)&url=\(tweetUrl)"
// encode a space to %20 for example
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
// cast to an url
let url = URL(string: escapedShareString)
// open in safari
UIApplication.shared.openURL(url!)
#ronatory's solution worked like charm. It also opens a Twitter application if it's already installed on the user's device.
For swift 5+ use UIApplication.shared.open(url!) instead of UIApplication.shared.openURL(url!) as it's deprecated.

Resources