I'm transferring a file from iOS to WatchOS. applicationContext and userInfo transfers all work fine. When I run the following code, nothing is transferred. fileTransfer.transferred == false.
let fileTransfer = WCSession.defaultSession().transferFile(fileurl, metadata: dict)
I can see all of my attempts queued up when I look at:
let transfers = WCSession.defaultSession().outstandingFileTransfers
Is there something I can check that will provide feedback as to why nothing is getting transferred? I'm using simulators. The file is a plist file. I'm accessing it like this:
let fileurl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("myfile", ofType: "plist")!)
fileurl does return the file path.
Related
As I understand from Apple documentation, that there is sandbox for each app , so there local storage to the app can save data and files inside it and the other apps can not access its data and files, but I tried to create file by app and retrieved file URL from it and create another app and pass the file URL to it, but the new app open this file successfully, why that happen? the other app must can not be able to open the file according to Apple documentation
In first App:
I download file using Alamofire
let destination: DownloadRequest.DownloadFileDestination =
{
(temporaryURL, response)in
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let tmpURL = documentsURL.appendingPathComponent("wordFile.docx")
return (tmpURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to:
destination).responseData { response in
(response.destinationURL?.path)!
//The "response.destinationURL?.path" is: "/Users/user/Library/Developer/CoreSimulator/Devices/A0427AC0-6D5E-4734-A550-73A8224BD54D/data/Containers/Data/Application/4126243E-E166-4311-A950-D8FF49A07991/Documents/wordFile.docx"
})
In second App:
I got the file path from previous App (response.destinationURL?.path)!
and pass it to webView , but the webView show file the successfully
I ran into this bug that prevents my app from displaying PDF using UIDocumentInteractionController or QLPreviewController: https://forums.developer.apple.com/thread/91835
According to the suggestions, the solution is to copy files to documents or tmp folders and load files from there.
However, this does not work for me. Loading the files from .documentDirectory or NSTemporaryDirectory() produces the same error, but now not only on device, but also in simulator.
Edit:
The following code solved the problem for me:
func copyFiles(fileName: String) -> URL {
let filemgr = FileManager.default
filemgr.delegate = self
let tempDocsFolder = URL.init(fileURLWithPath: NSTemporaryDirectory()).path
// my fileName is in format "file.pdf"
let fileSplit = fileName.components(separatedBy: ".")
let filePath = Bundle.main.path(forResource: fileSplit[0], ofType: fileSplit[1])
let destPath = "\(tempDocsFolder)/\(fileName)"
do {
try? filemgr.copyItem(atPath: filePath!, toPath: destPath)
}
return URL.init(fileURLWithPath: destPath)
}
Then returned URL is then feeded to the UIDocumentInteractionController. The reason it didn't work for me before was because I tried to copy my files to /tmp/documents/, but the files must be copied to the root of the tmp folder: /tmp/ (I have no idea why).
Check for case-sensitivity of resources(File names).
Add any screen shots of the code.
I decided to utilize Amazon S3 to upload files, however I find AWS Docs a bit confusing about S3 capabilities for iOS platform.
I would like to know how my app would act in the following scenarios:
Scenario 1: During the upload user has accidentally lost internet connection
Scenario 2: App crashes during the upload
I heard that iOS SDK takes care of such issues itself by resuming remaining upload when possible, I failed to find relevant information in docs, though.
Will AWSS3 framework cover both this scenarios? Does it need any additional lines od code to not be vulnerable for potential crashes and network errors?
I've found some relevant informations for Android platform
I'd love to know what can I expect from the following code
let image = UIImage(named: "12.jpeg")
let fileManager = FileManager.default
let imageData = UIImageJPEGRepresentation(image!, 0.99)
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("\(imageData!).jpeg")
fileManager.createFile(atPath: path as String, contents: imageData, attributes: nil)
let fileUrl = NSURL(fileURLWithPath: path)
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = "bucketname"
uploadRequest?.key = "folder/12.jpeg"
uploadRequest?.contentType = "image/jpeg"
uploadRequest?.body = fileUrl as URL!
uploadRequest?.serverSideEncryption = AWSS3ServerSideEncryption.awsKms
uploadRequest?.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
DispatchQueue.main.async(execute: {
print("bytes sent \(bytesSent), total bytes sent \(totalBytesSent), of total \(totalBytesExpectedToSend)")
})
}
let transferManager = AWSS3TransferManager.default()
transferManager?.upload(uploadRequest).continue(with: AWSExecutor.mainThread(), withSuccessBlock: { (taskk: AWSTask) -> Any? in
if taskk.error != nil {
// Error.
} else {
// Do something with your result.
}
return nil
})
Is it already crash/network proof?
EDIT:
This is the part of docs that sounds ambiguous to me:
S3 provides a multipart upload feature that lets you upload a single
object as a set of parts. Each part is a contiguous portion of the
object's data, and the object parts are uploaded independently and in
any order. If transmission of any part fails, you can retransmit that
part without affecting other parts. After all parts of the object are
uploaded, S3 assembles these parts and creates the object.
Does that mean it has its own inherent mechanism to manage that? Let's say I kill app during uploading a file, when I relaunch it and start over the upload process , will it start with the last chunk where it left off before I killed the app?
I'm working on an custom emoji keyboard in Swift and I'm having trouble finding and counting the images in a folder reference called "emojis".
EDIT: To clarify my issue is that let contents always end up as nil.
The structure from the location of the .xcodeproj file looks like this:
EmojiBoard/emojis/emoji-0.png and so on.
I've been trying to use the NSFileManager with no luck.
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath("emojis", error: &error)
println(contents)
This prints nil. I've also tried "EmojiBoard/emojis" and "/EmojiBoard/emojis".
I need this to determine how many images there are and loop them all out without having to resort to an insane switch statement or something like that.
Thank you!
P.S. Please note that I'm coding in Swift, not Objective C. I'm not proficient enough to convert C programming to swift I'm afraid. D.S.
if you created folder reference when adding the folder to your project use it like this (emojis folder icon is a blue folder):
let resourceURL = Bundle.main.resourceURL!.appendingPathComponent("emojis")
var resourcesContent: [URL] {
(try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
}
let emojiCount = resourcesContent.count
print(emojiCount)
if you created groups when adding the folder to your project use it like this (emojis folder icon is a yellow folder):
let resourceURL = Bundle.main.resourceURL!
let resourcesContent = (try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
let emojiCount = resourcesContent.filter { $0.lastPathComponent.hasPrefix("emoji-") }.count
print(emojiCount)
From the top of my head, without access to an IDE to test this code, I reckon something like this:
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath(path, error: &error)
for var index = 0; index < contents.count; ++index {
println("File is \(contents[index])")
}
If you replace 'path' above with your documents directory, this code should loop through the whole folder and print out all files.
If you just want the count of items just do this:
println("count is \(contents.count)")
The problem (or at least a major part of the problem) is your path. You can't pass in a path that's just a filename. You need an absolute path to one of the sandboxed directories available to your app like the documents directory.
Your code might look like this:
let documentsDir = NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask,
true)[0] as! NSString
let emojisPath = documentsDir.stringByAppendingPathCompnent("emojis")
let contents = fileManager.contentsOfDirectoryAtPath(emojisPath,
error: &error)
println(contents)
(That would work if your emojis folder is in your app's documents folder. If instead your emojis are in your app bundle (built into the app) you would need to use different code entirely (using NSBundle functions to get a path to the directory inside the bundle).
EDIT:
If you want to find files in your app's bundle use the NSBundle method resourcePath, and then append the folder name to the bundle's resourcePath using stringByAppendingPathCompnent, like the code above.
I've been trying to create a Today extension that needs access to a .plist file in the documents directory. I have setup the App group for both the app and the extension.
While I have seen examples for NSUserDefaults, I couldn't find anything for accessing files.
I tried accessing the file like this (which works in the app itself)
let paths = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as String
let filePath = "\(documentsDirectory)/config.plist"
if NSFileManager.defaultManager().fileExistsAtPath(filePath) // false
{
…
}
But I get the following error messages in the console:
Warning: CFFIXED_USER_HOME is not set! It should be set to the simulated home directory.
Failed to inherit CoreMedia permissions from 59919: (null)
The documentation says something about using NSFileCoordinator and NSFilePresenter. I couldn't find out how to use them though. I'm sure I'll need to tell them the app group identifier somewhere but I don't where.
I got it to work. Since I don't need to write the file from the extension, I don't think I need to use NSFileCoordinator. Turns out NSFileManager has a method containerURLForSecurityApplicationGroupIdentifier() for retrieving the container URL.
let manager = NSFileManager()
let containerURL = manager.containerURLForSecurityApplicationGroupIdentifier("group.MyGroupIdentifier")
let filePath = "\(containerURL.path)/config.plist"
let settings = NSDictionary(contentsOfFile: filePath)