Using reopened standard file descriptors in an iOS app with background capabilities? - ios

I would like to be able to redirect my logging statements to a file so that I can retrieve them when my app runs standalone (i.e. is not attached to Xcode). I have discovered (thank you Stackoverflow) that freopen can be used to accomplish this.
If I create a new Xcode project and add the code to redirect stderr then everything works as expected.
However, when I add the redirection code to my existing, bluetooth project I am having trouble. The file is being created and I can retrieve it using iTunes or Xcode's Devices window, but it is of size 0. If I explicitly close the file then the text that I wrote actually makes it into the file. It is as though iOS is not flushing the file when the app is terminated. I suspect that the trouble stems from the fact that I have enabled background processing. Can anyone help me to understand this?
Here is my code:
let pathes = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let filePath = NSURL(fileURLWithPath: pathes[0]).URLByAppendingPathComponent("Test.log")
freopen(filePath.path!, "a", stderr);
fputs("Hello, Samantha!\r\n", stderr);
struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(string: String) {fputs(string, stderr)}
}
var errStream = StderrOutputStream.stream
print("Hello, Robert", toStream: &errStream)
fclose(stderr) // Without this the text does not make it into the file.

I'd leave this as a comment, but have you looked into NSFileHandle? It sounds like you just need a way to append data to the end of a text file, correct?
Once you have a handle with something like NSFileHandle(forWritingToURL:), you can use .seekToEndOfFile() and .writeData(_:). As a side note, you'll need to convert your String to Data before writing it.
Admittedly, this will probably end up being more lines of code, and you'll almost certainly need to take threading into consideration.

Related

Swift 4 app crashes when open file from icloud

I have a problem that my app crashes when it is opening a file from iCloud. If I open this file from my app with a Document Picker, everything is fine. But if I try to open from outside my app, for example from iCloud or safari download it crashes. If I open it from local storage "my iphone" it is also working. It is interesting because it was good one week ago :)
So in AppDelegate, I've implemented the following method:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {}
According to the logs the crash occurs because the file does not exist.
file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Desktop/twic1121.pgn
This is the result if I print the URL from the parameter. I think this means that the file is there.
But if i do this: print(fm.fileExists(atPath: url.path)) then this is false.
So it is obvious that after let dataFromFile = fm.contents(atPath: url.path)
this is nil.
I have no idea what could be the problem here. So the real question here is why this is nil?
It appears that the error can be many things, all not related to the class you are applying the code (AppDelegate) nor the methods you are calling.
My guess is that the URL you are calling is not correctly built (not pointing to the correct object you are trying to point to). For many reasons.
See if one of this reasons fix your issue:
(1) The end of the URL you are calling had the suffix "pgn". If you are looking to load a picture, maybe the suffix is wrong. In that case it could have been some known and supported format like "png", "jpeg" or "jpg".
(2) The "%20"symbol at the middle of your code also lifts a flag. Does not seem to be a correct URL object of swift. Maybe the URL you are using is not represented in the correct way.
(3) com~apple~CloudDocs also lifts a flag, since it would unlikely have a "~" symbol in a URL passed. This also strongly suggests that maybe the URL you are using is not represented in the correct way.
I think your URL is not pointing to where you are trying to point to, resulting in the "does exist" method return false and the loading resulting in nil.
If all of this does not fix your issue, post more details of the code. Specially what method you are calling to build/create this URL object you are using, that points to: file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Desktop/twic1121.pgn

iOS reading from a file

I'm trying to get my iPhone app to load text from a file into a string array, with 1 line from the file per array element.
I've created an input file as a text file using sublime text. I dragged the file (which is located inside of a folder inside of my project directory) into xCode into a folder in the same location in the project heirarchy.
I also tried adding it as a bundle (by copying the folder and renaming it with the .bundle extension), to no avail. Currently, my app has the file in 2 places (Obviously I plan to delete the unneeded version, but I'm not sure how this will work so I've left it for now).
I've written a function that I want to read my file, and assemble its contents into an array:
func readFromFile(filename: String) -> [String]? {
guard let theFile = Bundle.main.path( forResource: fileName, ofType: "txt") else {
return nil // ALWAYS returns nil here: Seems 'filename' can't be found?????
}
do { // Extract the file contents, and return them as a split string array
let fileContents = try String(contentsOfFile: theFile)
return fileContents.components(separatedBy: "\n")
} catch _ as NSError {
return nil
}
}
As it stands, the function always returns nil at the location commented in the code.
I've been working on this for ~6hrs (and tried every suggestion I could find on StackOverflow, google etc) and I'm just getting more and more confused by the differences between the various versions of Swift and intricacies of iOS development. I can't seem to find a consistent answer anywhere. I've checked the apple documentation but it's too high level with no example code for me to understand at my swift beginner level.
I also tried naming the file with a ".txt" extension but that didn't help either.
The file must certainly be named alert01.txt if you are going to refer to it as forResource: "alert01", ofType: "txt".
Loading from a bundle will not work. The file needs to be part of your project as shown in the first entry.
However, your code is not going to work because you have created a folder reference. That means the folder PanicAlertFiles is being copied with all its contents into your bundle. Your code will need to dive into that folder in order to retrieve your file. Use path(forResource:ofType:inDirectory:) to do that, or (if you don't want to have to code the file name explicitly) get the folder and then use the FileManager to examine its contents.

How to set path to picture in folder in device in android appcelerator app

So I have app where I want to let users to share screenshot of score to facebook etc... I'm using SocialShare widget. In documentation it says to set path to image like this: "image:fileToShare.nativePath", but I'm not really sure how to set it. Another problem is that I need to share picture that has always different name, it saves screenshots with names like tia7828157.png,tia107997596.png... in folder in device internal memory in pictures/enigmania/ I'm new to appcelerator, so I dont know if there is something like wildcard I could use for this? Thanks for any help.
This is my code so far which I know is wrong, I know the widget works because it shares text without problem:
function shareTextWidget(e){
// share text status
var socialWidget=Alloy.createWidget('com.alcoapps.socialshare');
socialWidget.share({status:"Enigmania kvíz",androidDialogTitle:"hoho",image:test.png/pictures/enigmania});
}
You should use Ti.Filesystem class methods/properties to get the path of any file located on internal or external storage.
Also aware of the permissions of reading storage on Android 6+. Use Storage Permissions before accessing any file on Android 6+.
Simple code snippet to create a directory on internal storage at this location: pictures/enigmania and then write an image file of captured view in this directory.
function shareTextWidget(e){
var directory = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'pictures/enigmania');
!directory.exists() && directory.createDirectory();
var fileToShare = Ti.Filesystem.getFile(directory.resolve(), 'screen.jpg');
fileToShare.write($.SCREENSHOT_VIEW.toImage()); // write the blob image to created file
var socialWidget=Alloy.createWidget('com.alcoapps.socialshare');
socialWidget.share({status:"Enigmania kvíz",androidDialogTitle:"hoho",image:fileToShare.nativePath});
}
This code should work without any issues.
Note that $.SCREENSHOT_VIEW is the View ID for which you will take screenshot, so it depends on you how you maintain your View positions in order to capture correct screenshot, but point is to use Ti.UI.View toImage() method to capture the screenshot of particular view.
Let me know if this works for you or not, else we can look into other methods by getting your exact requirements. Good Luck!!!!

Is there a way to change the url path of a PDF manually and have it update real time?

I'm building an app for my school which includes a lunch menu, however since the lunch menu changes every month I don't want to keep updating my app just for that. I know you can open PDFs with Xcode either locally or online, but is there a way to change the url path of the pdf manually and have it update real time within the app. Any help would be much appreciated and I'm new to developing IOS apps, so any links that may help would be great.
If you control the website or have a line of communication with the person who does then you could agree that the latest menu always gets returned from example.com/current/lunch.pdf but really this should be set up as a GET request example.com/index.php?lunchmenu=current so that it is down to the website to respond with the file or the file location rather than the app's responsibility to guess the filename. So for example:
if let url = NSURL(string: "http://www.example.com/index.php?lunchmenu=current") {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let dataTask = session.dataTaskWithURL(url, completionHandler: {(d,_,_) in
if let data = d {
String(data:data, encoding:NSUTF8StringEncoding) // this is could be your file name
}
})
dataTask.resume()
}
It would then be possible to perform other requests like: example.com/index.php?lunchmenu=nextmonth. Working in this way means that if for some reason the naming pattern or location of the files changed your app would still keep working.
If you don't have access to the school website but do know where the file is stored, you could query your own website for the file information and either update this automatically (or if there was no other way - manually). Again, this would prevent an app update if the structure of the school website changed.
Only rely on static file locations and naming systems if you really have to.

XNA SoundEffect fails to be loaded from file

I got a dictionary to store SoundEffects in, like:
public static Dictionary<string, SoundEffect> Hangok = new Dictionary<string, SoundEffect>();
I load sounds from files (normal .wav format), like:
GStatic.Hangok.Add(Azonosító, SoundEffect.FromStream(File.OpenRead(Azonosító)));
, where Azonosító was the filename.
All is just fine, files are loaded, except one; an exception is created:
Operation is not valid due to the current state of the object.
, what is not much of information for me. Could anyone explain this error message OR tell me why SoundEffect.FromStream fails to read? Why? When? Workaround?
Thanks in advance:
Péter
I use the ContentManager to load in SoundEffect's. Place the wav file in the content project and it should just load in.
E.g.
SoundEffect s = Content.Load<SoundEffect>("name");
Not a complete, but working solution to this problem. "Answering my question" only, because it may be useful for other developers, who also have no idea what the problem may be.
try
{
GStatic.Hangok.Add(Azonosító, SoundEffect.FromStream(File.OpenRead(Azonosító)));
}
catch
{
GStatic.Hangok.Add(Azonosító, new SoundEffect(File.ReadAllBytes(Azonosító), 11025, AudioChannels.Mono));
}
And well: I got no idea WHY you can not load that file in the normal way and why you can load the way like in the exception handler. Having a file in mono should not be that big problem. If someone knows, please drop a note/comment.

Resources