Posting local image file using graph API - react-native

I'm hoping to POST to the graph API's /[event_id]/photos endpoint to allow a user to upload to one of their events. The documentation makes it seem like it is possible to upload a local file attachment instead of specifying a url of an image already on the internet.
I'm using the react-native-fbsdk library, but I can't figure out how to upload the photo. Here is what I have right now:
sharePhotoToEvent: (eventId, imageUrl) => {
return new Promise((resolve, reject) => {
const eventsRequest = new GraphRequest(
`/${eventId}/photos`,
{
httpMethod: 'POST',
parameters: {
url: imageUrl
}
},
(error, result) => {
if (error) {
console.log('Event photo upload error:');
console.log(error);
reject(error);
} else if (result) {
console.log(result);
resolve(result);
} else {
reject();
}
}
);
// Start the graph request.
new GraphRequestManager().addRequest(eventsRequest).start();
});
}
The imageUrl is the file path to the local image saved on device. Do I need to use a different undocumented parameter than "url"? Is there some other step that I need to do other than just providing the local file path?
The local file path is of the form:
file:///var/mobile/Containers/Data/Application/D3394FBD8-91E3-48B0-E32E-A1KDN831349E/Documents/mimi_image.jpg
Here is the error response I am getting:
{ domain: 'com.facebook.sdk.core',
message: 'The operation couldn’t be completed. (com.facebook.sdk.core error 8.)',
userInfo:
{ NSRecoveryAttempter: null,
NSLocalizedRecoverySuggestion: 'The server is temporarily busy, please try again.',
'com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey':
{ code: 500,
body:
{ error:
{ type: 'OAuthException',
message: 'An unknown error has occurred.',
fbtrace_id: 'DE2PvnZlqm8',
code: 1 } } },
'com.facebook.sdk:FBSDKErrorDeveloperMessageKey': 'An unknown error has occurred.',
'com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey': 500,
'com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode': 1,
'com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey': 1,
NSLocalizedRecoveryOptions: [ 'OK' ] },
nativeStackIOS:
[ '0 mimi 0x0000000100dd6148 RCTJSErrorFromCodeMessageAndNSError + 152',
'1 mimi 0x0000000100dd6070 RCTJSErrorFromNSError + 264',
'2 mimi 0x00000001010c8590 __48-[RCTFBSDKGraphRequestConnectionContainer start]_block_invoke + 156',
'3 mimi 0x0000000100b35c2c -[FBSDKGraphRequestMetadata invokeCompletionHandlerForConnection:withResults:error:] + 152',
'4 mimi 0x0000000100b3ca9c __82-[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:]_block_invoke + 160',
'5 mimi 0x0000000100b3c8e8 -[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:] + 956',
'6 mimi 0x0000000100b3e568 __76-[FBSDKGraphRequestConnection processorDidAttemptRecovery:didRecover:error:]_block_invoke + 64',
'7 mimi 0x0000000100b35c2c -[FBSDKGraphRequestMetadata invokeCompletionHandlerForConnection:withResults:error:] + 152',
'8 mimi 0x0000000100b3ca9c __82-[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:]_block_invoke + 160',
'9 mimi 0x0000000100b3c8e8 -[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:] + 956',
'10 mimi 0x0000000100b3c388 __64-[FBSDKGraphRequestConnection completeWithResults:networkError:]_block_invoke + 400',
'11 CoreFoundation 0x0000000181f9b988 <redacted> + 216',
'12 mimi 0x0000000100b3c124 -[FBSDKGraphRequestConnection completeWithResults:networkError:] + 556',
'13 mimi 0x0000000100b3b4f0 -[FBSDKGraphRequestConnection completeFBSDKURLSessionWithResponse:data:networkError:] + 1012',
'14 mimi 0x0000000100b39638 __36-[FBSDKGraphRequestConnection start]_block_invoke_2 + 80',
'15 libdispatch.dylib 0x0000000103b6d49c _dispatch_call_block_and_release + 24',
'16 libdispatch.dylib 0x0000000103b6d45c _dispatch_client_callout + 16',
'17 libdispatch.dylib 0x0000000103b72050 _dispatch_main_queue_callback_4CF + 1192',
'18 CoreFoundation 0x0000000182069eb0 <redacted> + 12',
'19 CoreFoundation 0x0000000182067a8c <redacted> + 2012',
'20 CoreFoundation 0x0000000181f87fb8 CFRunLoopRunSpecific + 436',
'21 GraphicsServices 0x0000000183e1ff84 GSEventRunModal + 100',
'22 UIKit 0x000000018b55c2e8 UIApplicationMain + 208',
'23 mimi 0x0000000100a5d3e4 main + 124',
'24 libdyld.dylib 0x0000000181aaa56c <redacted> + 4' ],
code: 'ECOM.FACEBOOK.SDK.CORE8' }

Related

WifiManager.connectToProtectedSSID - most likely the callback was already invoked

I got this error when trying to use react-native-wifi-reborn to connect with with
Invariant Violation: No callback found with cbID 2567 and callID 1283 for WifiManager.connectToProtectedSSID - most likely the callback was already invoked. Args: '[{"code":"unableToConnect","message":"internal error.","domain":"NEHotspotConfigurationErrorDomain","userInfo":{"NSLocalizedDescription":"internal error."},"nativeStackIOS":["0 wifiborn 0x0000000100f47024 RCTJSErrorFromCodeMessageAndNSError + 120","1 wifiborn 0x0000000100eddad4 __41-[RCTModuleMethod processMethodSignat...(truncated)...","2 wifiborn 0x0000000100e3c55c __77-[WifiManager connectToProtectedSSID:...(truncated)...","3 NetworkExtension 0x00000001ad1427ac 9AAC742E-D5F7-3619-BC05-EA4F2D8601FB + 505772","4 libdispatch.dylib 0x0000000103f18064 _dispatch_call_block_and_release + 32","5 libdispatch.dylib 0x0000000103f19d90 _dispatch_client_callout + 20","6 libdispatch.dylib 0x0000000103f2a058 _dispatch_main_queue_callback_4CF + 1040","7 CoreFoundation 0x000000019bb581f8 58500388-BF36-397C-84CF-17315A3445B6 + 668152","8 CoreFoundation 0x000000019bb520d0 58500388-BF36-397C-84CF-17315A3445B6 + 643280","9 CoreFoundation 0x000000019bb511c0 CFRunLoopRunSpecific + 600","10 GraphicsServices 0x00000001b3139734 GSEventRunModal + 164","11 UIKitCore 0x000000019e5bf7e4 186C18FD-1082-3811-A761-88E8376C7E69 + 12363748","12 UIKitCore 0x000000019e5c5054 UIApplicationMain + 168","13 wifiborn 0x0000000100975950 main + 120","14 libdyld.dylib 0x000000019b80dcf8 B08AB7C2-64E8-3937-9487-C33D0175FD34 + 7416"]}]'
Simply using this function:
const connectWithWifi = async () => {
try {
//initWifi();
const data = await WifiManager.connectToProtectedSSID(
ssid,
password,
false,
);
console.log('Connected successfully!', {data});
setConnected({connected: true, ssid});
} catch (error) {
setConnected({connected: false, error: error.message});
console.log('Connection failed!', {error});
}
};
someone can Help me?

App rejected: React Native app crashed when opening image crop picker

No issues or crashes with app on build mode and in 3 different devices.
App got rejected by App Store review.
Rejection reason: The app crashed when we selected the image uploader.
Now I'm need guidance trying to figure out what the cause of the crash is because I can't recreate it. And before considering using another image picker package I would like to try to make sense of this crash first.
Additional Information
"react-native": "0.57.1",
"react-native-image-crop-picker": "^0.21.3",
"rn-fetch-blob": "^0.10.14"
Library used: https://github.com/ivpusic/react-native-image-crop-picker
Code used (Is anything missing?):
openPhotoPicker() {
const { currentUser } = firebase.auth()
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
ImagePicker.openPicker({
width: 60,
height: 60,
compressImageMaxWidth: 800,
compressImageMaxHeight: 800,
compressImageQuality: 0.8,
cropping: true,
smartAlbums: ['UserLibrary', 'Favorites'],
mediaType: 'photo'
}).then(image => {
const imagePath = image.path
let uploadBlob = null
const imageRef = firebase.storage()
.ref(`/users/${currentUser.uid}/progress`)
.child(`${toJSONLocal(this.state.newDate)}.jpg`)
let mime = 'image/jpg'
fs.readFile(imagePath, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
let obj = {}
obj["progressPhoto"] = url
this.setState(obj)
this.addPhotoDatabase() // Photo uploaded to firebase storage is also uploaded to database so it can be referenced.
})
.catch((error) => {
console.log(error);
})
})
.catch((error) => {
console.log(error);
});
}
Here's the symbolicated crash report:
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 1
Application Specific Information:
abort() called
Last Exception Backtrace:
0 CoreFoundation 0x1b64cf518 __exceptionPreprocess + 228
1 libobjc.A.dylib 0x1b56aa9f8 objc_exception_throw + 55
2 MyApp 0x10048a3f8 RCTFatal + 222200 (RCTAssert.m:132)
3 MyApp 0x100486938 -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 207160 (RCTExceptionsManager.m:58)
4 CoreFoundation 0x1b64d6ba0 __invoking___ + 143
5 CoreFoundation 0x1b63b8c90 -[NSInvocation invoke] + 291
6 CoreFoundation 0x1b63b98c4 -[NSInvocation invokeWithTarget:] + 59
7 MyApp 0x10049eaa0 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 305824 (RCTModuleMethod.mm:550)
8 MyApp 0x1004e5750 facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 595792 (RCTNativeModule.mm:104)
9 MyApp 0x1004e54ac invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 595116 (RCTNativeModule.mm:71)
10 libdispatch.dylib 0x1b5f0fa38 _dispatch_call_block_and_release + 23
11 libdispatch.dylib 0x1b5f107d4 _dispatch_client_callout + 15
12 libdispatch.dylib 0x1b5eb9320 _dispatch_lane_serial_drain$VARIANT$mp + 591
13 libdispatch.dylib 0x1b5eb9e3c _dispatch_lane_invoke$VARIANT$mp + 427
14 libdispatch.dylib 0x1b5ec24a8 _dispatch_workloop_worker_thread + 595
15 libsystem_pthread.dylib 0x1b60f0114 _pthread_wqthread + 303
16 libsystem_pthread.dylib 0x1b60f2cd4 start_wqthread + 3
Thread 1 name: Dispatch queue: com.facebook.react.ExceptionsManagerQueue
Thread 1 Crashed:
0 libsystem_kernel.dylib 0x00000001b606d0dc __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001b60e6094 pthread_kill$VARIANT$mp + 380
2 libsystem_c.dylib 0x00000001b5fc6ea8 abort + 140
3 libc++abi.dylib 0x00000001b5693788 __cxa_bad_cast + 0
4 libc++abi.dylib 0x00000001b5693934 default_unexpected_handler+ 6452 () + 0
5 libobjc.A.dylib 0x00000001b56aae00 _objc_terminate+ 24064 () + 124
6 libc++abi.dylib 0x00000001b569f838 std::__terminate(void (*)+ 55352 ()) + 16
7 libc++abi.dylib 0x00000001b569f8c4 std::terminate+ 55492 () + 84
8 libdispatch.dylib 0x00000001b5f107e8 _dispatch_client_callout + 36
9 libdispatch.dylib 0x00000001b5eb9320 _dispatch_lane_serial_drain$VARIANT$mp + 592
10 libdispatch.dylib 0x00000001b5eb9e3c _dispatch_lane_invoke$VARIANT$mp + 428
11 libdispatch.dylib 0x00000001b5ec24a8 _dispatch_workloop_worker_thread + 596
12 libsystem_pthread.dylib 0x00000001b60f0114 _pthread_wqthread + 304
13 libsystem_pthread.dylib 0x00000001b60f2cd4 start_wqthread + 4

Alamofire 3.5.1 crashed when cancel the upload request

I just followed cnoon's suggest for the request cancel, the steps like:
post the multipartFormData upload request;
catch the upload progress and get the Alamofire.Request in the encodingCompletion;
do cancel request;
Then the crash is coming.
All of the upload related code as below:
private var request: Alamofire.Request?
func upload() {
Alamofire.upload(
.POST,
"\(AppManager_Inst.currentServerAddress)/cloud/uploadFile",
multipartFormData: { [unowned self] multipartFormData in
if self.uploadFile.data.isKindOfClass(UIImage),
let image = self.uploadFile.data as? UIImage,
let imageData = UIImagePNGRepresentation(image) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "\(self.uploadFile.name).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { [unowned self] encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
self.request = upload
upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
dispatch_async(dispatch_get_main_queue()) {
let buffer = ["file": "\(self.uploadFile.id)", "speed": "\(bytesRead)", "readed": "\(totalBytesRead)", "all": "\(totalBytesExpectedToRead)"]
GlobalBroadcast_Inst.broadcastMsg(.uploading, msg: buffer)
}
}
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})
case .Failure(let error):
self.uploading = false
print(error)
}
}
)
}
request?.cancel()
The crash info as below:
*** Terminating app due to uncaught exception 'UninitializedMessage', reason: ''
*** First throw call stack:
(
0 CoreFoundation 0x000000010ceb2d85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010f322deb objc_exception_throw + 48
2 ProtocolBuffers 0x000000010bb72b69 -[PBGeneratedMessageBuilder checkInitialized] + 169
3 CommonFoundation 0x000000010bd1a17b -[NewFileRespBuilder build] + 43
4 CommonFoundation 0x000000010bd18942 +[NewFileResp parseFromData:] + 130
5 QBCloud 0x000000010b690fe0 _TFFFC7QBCloud8Uploader6uploadFT_T_U0_FOC9Alamofire7Manager31MultipartFormDataEncodingResultT_U0_FGVS1_8ResponseCSo6NSDataCSo7NSError_T_ + 448
6 Alamofire 0x000000010b92c0d7 _TTRXFo_oGV9Alamofire8ResponseCSo6NSDataCSo7NSError__dT__XFo_iGS0_S1_S2___dT__ + 151
7 Alamofire 0x000000010b92bc4d _TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 797
8 Alamofire 0x000000010b92a494 _TPA__TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 164
9 Alamofire 0x000000010b8e3bf7 _TTRXFo__dT__XFdCb__dT__ + 39
10 libdispatch.dylib 0x0000000110578d9d _dispatch_call_block_and_release + 12
11 libdispatch.dylib 0x00000001105993eb _dispatch_client_callout + 8
12 libdispatch.dylib 0x00000001105811ef _dispatch_main_queue_callback_4CF + 1738
13 CoreFoundation 0x000000010ce0c0f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
14 CoreFoundation 0x000000010cdcdb99 __CFRunLoopRun + 2073
15 CoreFoundation 0x000000010cdcd0f8 CFRunLoopRunSpecific + 488
16 GraphicsServices 0x0000000113cd3ad2 GSEventRunModal + 161
17 UIKit 0x000000010dda5f09 UIApplicationMain + 171
18 QBCloud 0x000000010b692b42 main + 114
19 libdyld.dylib 0x00000001105ce92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type
Does anyone can help on this?
I find the root cause of my problem is the response.data is 0 bytes NSData, so the parseFromData of protobuf failed:
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})

Render HTML with images using PhantomJS

I am trying to create a PDF from HTML text using PhantomJS (version 1.9.7). I've written a very simple script (made more complicated by error callbacks etc.)
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stdout.write(msgStack.join('\n'));
phantom.exit(1);
};
var page = require('webpage').create();
page.viewportSize = { width: 800, height: 600 };
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
page.render('tmp.pdf');
setTimeout(function() {
phantom.exit();
}, 5000);
I set up the page, assign the simple HTML string to the content property and render it to a PDF.
This script doesn't produce any output.
I've narrowed the problem down to the <img> element, when that is removed a PDF is generated as expected. I can see from the callback functions that the image is requested, a response is received, and there are no errors reported. I've tried rendering to a PNG which also yields no output.
I've explored the possibility of this being a proxy issue, however the raserize.js example works without any problems.
You have to call render when the page is fully loaded. Remember that loading a page via page.open or page.content is always async.
Change your code to this
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
setTimeout(function() {
page.render('tmp.pdf');
phantom.exit();
}, 5000);

Cannot read property 'opacity' of undefined

I am loading the fine uploader in this manner:
var uploader = new qq.FineUploaderBasic({
button: $("#docAddHref"),
request: {
endpoint: 'server/handleUploads'
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 204800 // 200 kB = 200 * 1024 bytes
},
callbacks: {
onSubmit: function (id, fileName) {
$messages.append('<div id="file-' + id + '" class="alert" style="margin: 20px 0 0"></div>');
},
onUpload: function (id, fileName) {
$('#file-' + id).addClass('alert-info')
.html('<img src="client/loading.gif" alt="Initializing. Please hold."> ' +
'Initializing ' +
'“' + fileName + '”');
},
onProgress: function (id, fileName, loaded, total) {
if (loaded < total) {
progress = Math.round(loaded / total * 100) + '% of ' + Math.round(total / 1024) + ' kB';
$('#file-' + id).removeClass('alert-info')
.html('<img src="client/loading.gif" alt="In progress. Please hold."> ' +
'Uploading ' +
'“' + fileName + '” ' +
progress);
} else {
$('#file-' + id).addClass('alert-info')
.html('<img src="client/loading.gif" alt="Saving. Please hold."> ' +
'Saving ' +
'“' + fileName + '”');
}
},
onComplete: function (id, fileName, responseJSON) {
if (responseJSON.success) {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-success')
.html('<i class="icon-ok"></i> ' +
'Successfully saved ' +
'“' + fileName + '”' +
'<br><img src="img/success.jpg" alt="' + fileName + '">');
} else {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-error')
.html('<i class="icon-exclamation-sign"></i> ' +
'Error with ' +
'“' + fileName + '”: ' +
responseJSON.error);
}
},
onError: function (id, name, reason, xhr) {
$('#fubErrorAlert .message').text(reason);
$('#fubErrorAlert button').click(function () {
$('#fubErrorAlert').hide();
});
$('#fubErrorAlert').show();
}
}
});
console.log('uploader called');
uploader();
When the page loads I am getting this javascript error:
Cannot read property 'opacity' of undefined
I installed the FineUploader via Nuget Pacakage for ASP.NET
https://github.com/Widen/fine-uploader-server/tree/master/ASP.NET%20MVC%20C%23
Please advice!
Your button option is likely the problem. You should change it to:
button: $("#docAddHref")[0]
If you want to do things like pass in a jQuery object, you will need to download and use Fine Uploader's jQuery plugin. More info about the plugin at http://docs.fineuploader.com/integrating/jquery.html