ccgus / CocoaScript

JavaScript + the Cocoa frameworks, and then ObjC brackets show up to party as well.
Other
618 stars 58 forks source link

NSURLSessionUploadTask delegate :didSendBodyData cause sketch crash #62

Closed hyhajnal closed 5 years ago

hyhajnal commented 5 years ago

I want to get the progress when upload a zip file, so I use NSURLSessionUploadTask delegate URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:

the file uploaded successfully, but it causes sketch exit and the log shows "Sketch XPC connection invalidated".

while other delegate like connection:didReceiveResponse: works well, here is my code:

uploadZip: function(_filePath) {
        var filePath = _filePath + '.zip';
        // filePath = '/var/folders/91/b8j740hj5gnb00705gbrk9200000gn/T/com.sketch.cosa/1550117625580save.zip'
        var self = this;
        log(self.uploadParams);
        self.CONFIGS = self.setConfigs({userName: self.uploadParams.userName || ''});
        var paramStr = self.queryStringify(self.uploadParams, true);

        var res = null;

        var delegate = new MochaJSDelegate({
             "URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:": function(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) {
                 log('didSendBodyData');
                 // var progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
                 log(totalBytesSent);
                 coscript.setShouldKeepAround(false);
             },
            "URLSession:task:didCompleteWithError:": function(session, task, error) {
                log('didCompleteWithError');
                coscript.setShouldKeepAround(false);
            }
            // "connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:": function(connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) {
            //     log('didSendBodyData');
            //     // var progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
            //     // log(totalBytesWritten);
            //     // coscript.setShouldKeepAround(false);
            // },
            // 'connection:didReceiveResponse:': function (connection, httpResponse) {
            //     log('didReceiveResponse');
            //     self.connection.cancel();
            //     // log(httpResponse);
            //     // coscript.setShouldKeepAround(false);
            // },
            // 'connection:didReceiveData:': function (connection, data) {
            //     log('didReceiveData');
            //     var result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]
            //     log(result);
            //     self.connection.cancel();
            //     // coscript.setShouldKeepAround(false);
            // }
        });
        var delegateInstance = delegate.getClassInstance();

        var url = NSURL.alloc().initWithString('https://xxx.com/api/detail/uploadUIResource?' + paramStr)
        var boundary = 'WebKitFormBoundaryVGek9xDAAf0OmBfg';
        var request =  NSMutableURLRequest.requestWithURL(url);
        request.setHTTPMethod('POST');
        request.setValue_forHTTPHeaderField('multipart/form-data; boundary=----' + boundary, 'Content-Type')

        var uploadData = NSMutableData.data()
        // _data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:nil];
        var fileData = NSData.dataWithContentsOfFile_options_error(filePath, NSDataReadingMappedIfSafe, nil);
        var file = {
            name: 'file',
            fileName: filePath.split('/').pop(),
            mimeType: 'application/zip'
        }

        uploadData.appendData(
            NSString.alloc()
              .initWithString("------" + boundary + "\r\n")
              .dataUsingEncoding(NSUTF8StringEncoding)
        )
        uploadData.appendData(
            NSString.alloc()
                .initWithString("Content-Disposition: form-data; name=\"" + file.name + "\"; filename=\"" + file.fileName + "\"\r\nContent-Type: " + file.mimeType + "\r\n\r\n")
                .dataUsingEncoding(NSUTF8StringEncoding)
        )
        uploadData.appendData(fileData);
        uploadData.appendData(
            NSString.alloc()
              .initWithString("\r\n")
              .dataUsingEncoding(NSUTF8StringEncoding)
        )
        uploadData.appendData(
            NSString.alloc()
              .initWithString("------" + boundary + "--\r\n")
              .dataUsingEncoding(NSUTF8StringEncoding)
        )
        // request.setHTTPBody(uploadData);
        request.setValue_forHTTPHeaderField('' + uploadData.length(), 'Content-Length')

        // var response = MOPointer.alloc().init()
        // var error = MOPointer.alloc().init()
        // var data = [NSURLConnection sendSynchronousRequest:request returningResponse:response error:error];

        // if (data.length > 0) {
        //     var res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        //     log(res);
        // }

        // [_connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
        //                    forMode:NSDefaultRunLoopMode];
        // coscript.setShouldKeepAround(false);
        // self.connection = NSURLConnection.alloc().initWithRequest_delegate(request,delegateInstance);
        // self.connection.start();
        // NSOperationQueue.mainQueue()
        var session = NSURLSession.sessionWithConfiguration_delegate_delegateQueue(NSURLSessionConfiguration.defaultSessionConfiguration(), delegateInstance, nil);
        var task = session.uploadTaskWithRequest_fromData(request, uploadData)
        task.resume();
        session.finishTasksAndInvalidate();
        // session.invalidateAndCancel();
    },
ccgus commented 5 years ago

I'm not sure, I'm guessing the delegate is going away somehow.

hyhajnal commented 5 years ago

@ccgus I'm guessing the delegate maybe causes a memory leak or other problems which leads to sketch crashed. Thanks for your replay, I will try another way

wangcheng007 commented 4 years ago

did you solve the problem?

uncleLian commented 3 years ago

@hyhajnal 请问最后解决办法有吗?我也正在寻求实现上传进度的方法