no file in transfer queue through WatchConnectivity and WCSession - watchkit

I'm trying to send a data file from Apple Watch to paired iPhone through WatchConnectivity. My code is as following:
let data = try? JSONSerialization.data(withJSONObject: self.storedData, options : .prettyPrinted)
let str = String(data: data!, encoding: String.Encoding.utf8)
print(str)
var fileName = ""
let tempDirectory = NSTemporaryDirectory()
fileName = tempDirectory + "test.json"
if self.fileManager.createFile(atPath: fileName, contents: data
, attributes: nil) {
print("New file creation went through!")
}
if self.fileManager.fileExists(atPath: fileName) {
print("File created # \(fileName)")
} else {
print("Something wrong when creating file # \(fileName)")
}
var fileTransferString = "file://"
fileTransferString += fileName
let url = URL(string: fileTransferString)
self.session.transferFile(url!, metadata: nil)
print("\(self.session.outstandingFileTransfers.count) files in the transfer queue!")
Although I got the message that "File created #...", the following message by the last line "print" is always "0 files in the transfer queue!" I didn't find any object failed to initiate or nil throughout the process. It just seems that the file was created but the "session.transferFile" function just didn't go through.
Can anybody help me on some hints regarding where the problem is and how to solve it?
Thank you all!
Paul

Try changing the last two lines to:
self.session.transferFile(url!, metadata: nil)
DispatchQueue.global(attributes: .qosUserInitiated).async {
print("\(self.session.outstandingFileTransfers.count) files in the transfer queue!")
}
Any difference?

Related

Receiving <Fault -32700: 'parse error. not well formed'> when trying to upload video to WordPress using xmlrpc.client

Pretty much the title, attaching the python code below.
I'm trying to download files from a specific source and upload them to a WordPress site.
Photos work great, and videos return the following message on wp.call(UploadFile(data)):
<Fault -32700: 'parse error. not well formed'>
Tried using different methods for encoding to base64, reading Wordpress_xmlrpc documentation, nothing.
It's worth mentioning that this method did work on the "Demo" site, and now on once we moved to the "real" site it returns this error.
Any ideas?
def UploadPicture(PathOfFile, Type):
wp = Client(url ,user, password)
filename = PathOfFile #pathofvideo
#Setup
if Type == "jpg":
data = {
'name': 'picture.jpg',
'type': 'image/jpeg', # mimetype
}
if Type == "mp4":
data = {
'name': 'clip.mp4',
'type': 'video/mp4', # mimetype
}
# read the binary file and let the XMLRPC library encode it into base64
with open(filename, 'rb') as img:
data['bits'] = xmlrpc_client.Binary(img.read())
#upload and return ID
response = wp.call(media.UploadFile(data))
attachment_id = response['id']
return(attachment_id)

Alamofire v4, Swift v3 Uploading Sqlite file to domain

I’m trying to upload an Sqlite database from IOS Swift 3 to my server using Alamofire 4.0, but having problems converting the sqlite file into the data type required to upload.
The majority of posts / question examples seem to default to uploading images, but I am struggling to find example of uploading sqlite or other file types (for back-up purposes)
I have searched for the basic code and found this so far which looks very reasonable (thanks to following post: Alamofire 4 upload with parameters)
let parameters = ["file_name": "swift_file.jpeg"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 1)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"http://sample.com/upload_img.php")
{ (result) in
switch result
{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
//print response.result
}
case .failure(let encodingError):
//print encodingError.description
}
}
The part I’m struggling with is to append the sqlite file to the upload (multipartFormData.append(………..?) I’ve searched but not found any good reference posts.
Yes, i’m a newbe, but trying hard, any help would be appreciated…..
It's exactly the same as the image example except that the mime type would be application/octet-stream.
Also, you'd probably go ahead and load it directly from the fileURL rather than loading it into a Data first.
As an aside, the parameters in that example don't quite make sense, as it looks redundant with the filename provided in the upload of the image itself. So you'd use whatever parameters your web service requires, if any. If you have no additional parameters, you'd simply omit the for (key, value) { ... } loop entirely.
Finally, obviously replace the file field name with whatever field name your web service is looking for.
// any additional parameters that must be included in the request (if any)
let parameters = ["somekey": "somevalue"]
// database to be uploaded; I'm assuming it's in Documents, but perhaps you have it elsewhere, so build the URL appropriately for where the file is
let filename = "test.sqlite"
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent(filename)
// now initiate request
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(fileURL, withName: "file", fileName: filename, mimeType: "application/octet-stream")
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: urlString) { result in
switch result {
case .success(let upload, _, _):
upload
.authenticate(user: self.user, password: self.password) // only needed if you're doing server authentication
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
print("\(response.result.value)")
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
}
Unrelated, but if you're ever unsure as to what mime type to use, you can use this routine, which will try to determine mime type from the file extension.
/// Determine mime type on the basis of extension of a file.
///
/// This requires MobileCoreServices framework.
///
/// - parameter url: The file `URL` of the local file for which we are going to determine the mime type.
///
/// - returns: Returns the mime type if successful. Returns application/octet-stream if unable to determine mime type.
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream";
}

Request without output Swift 3

I have that code
typealias escHandler = ( URLResponse?, Data? ) -> Void
func getRequest(url : URL, _ handler : #escaping escHandler){
let session = URLSession.shared
let task = session.dataTask(with: url){ (data,response,error) in
print("--")
handler(response,data)
}
task.resume()
}
I wanna get output from this call, but, for some reason the program just finish without output.
let x = "someURL"
let url = URL(string: x)!
getRequest(url: url){ response,data in
print("Handling")
}
That's my problem, can anyone help me?
The code is correct but if by any chance you are using a "http" URL and not a "https" url then you have to make the following change to the info.plist file
Add "App Transport Security Settings" -> Add "Allow Arbitrary Loads" and set it to "YES".
Refer the screenshot below

FileReference.download() works for .jpg .txt but not .dgn files in flex

In downloading files using the following codes, it surprised me that it succeeded in downloading .jpg .txt files BUT .dgn format file return IO Error #2038
Could somebody give me any advice? Thanks in advance.
protected function init(event:FlexEvent):void
{
fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, doEvent);
fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
}
private function doEvent(evt:Event):void
{
var fr:FileReference = evt.currentTarget as FileReference;
switch (evt.type)
{
case "complete":
Alert.show("File : " + fr.name + " download succeed");
break;
default :
Alert.show("Error occur during downloading !!!");
break;
}
protected function downLoadLICMap(event:MouseEvent):void
{
urlReq = new URLRequest("http://svygis/viewphoto/ceddphoto/20130916 raw/1se19d.dgn");
fileRef.download(urlReq);
}
I suspect Flex is not at fault here. It would rather be a server setting issue.
Have you tried opening that URL directly in the browser? You probably will not be able to download the file like that either.
If that's the case, you only need to configure a mime type for the .dgn extension on your web server.

In Node.JS, when I do a POST request, what is the maximum size? [duplicate]

I created an upload script in node.js using express/formidable. It basically works, but I am wondering where and when to check the uploaded file e. g. for the maximum file size or if the file´s mimetype is actually allowed.
My program looks like this:
app.post('/', function(req, res, next) {
req.form.on('progress', function(bytesReceived, bytesExpected) {
// ... do stuff
});
req.form.complete(function(err, fields, files) {
console.log('\nuploaded %s to %s', files.image.filename, files.image.path);
// ... do stuff
});
});
It seems to me that the only viable place for checking the mimetype/file size is the complete event where I can reliably use the filesystem functions to get the size of the uploaded file in /tmp/ – but that seems like a not so good idea because:
the possibly malicious/too large file is already uploaded on my server
the user experience is poor – you watch the upload progress just to be told that it didnt work afterwards
Whats the best practice for implementing this? I found quite a few examples for file uploads in node.js but none seemed to do the security checks I would need.
With help from some guys at the node IRC and the node mailing list, here is what I do:
I am using formidable to handle the file upload. Using the progress event I can check the maximum filesize like this:
form.on('progress', function(bytesReceived, bytesExpected) {
if (bytesReceived > MAX_UPLOAD_SIZE) {
console.log('### ERROR: FILE TOO LARGE');
}
});
Reliably checking the mimetype is much more difficult. The basic Idea is to use the progress event, then if enough of the file is uploaded use a file --mime-type call and check the output of that external command. Simplified it looks like this:
// contains the path of the uploaded file,
// is grabbed in the fileBegin event below
var tmpPath;
form.on('progress', function validateMimetype(bytesReceived, bytesExpected) {
var percent = (bytesReceived / bytesExpected * 100) | 0;
// pretty basic check if enough bytes of the file are written to disk,
// might be too naive if the file is small!
if (tmpPath && percent > 25) {
var child = exec('file --mime-type ' + tmpPath, function (err, stdout, stderr) {
var mimetype = stdout.substring(stdout.lastIndexOf(':') + 2, stdout.lastIndexOf('\n'));
console.log('### file CALL OUTPUT', err, stdout, stderr);
if (err || stderr) {
console.log('### ERROR: MIMETYPE COULD NOT BE DETECTED');
} else if (!ALLOWED_MIME_TYPES[mimetype]) {
console.log('### ERROR: INVALID MIMETYPE', mimetype);
} else {
console.log('### MIMETYPE VALIDATION COMPLETE');
}
});
form.removeListener('progress', validateMimetype);
}
});
form.on('fileBegin', function grabTmpPath(_, fileInfo) {
if (fileInfo.path) {
tmpPath = fileInfo.path;
form.removeListener('fileBegin', grabTmpPath);
}
});
The new version of Connect (2.x.) has this already baked into the bodyParser using the limit middleware: https://github.com/senchalabs/connect/blob/master/lib/middleware/multipart.js#L44-61
I think it's much better this way as you just kill the request when it exceeds the maximum limit instead of just stopping the formidable parser (and letting the request "go on").
More about the limit middleware: http://www.senchalabs.org/connect/limit.html

Resources