Skip to content

Instantly share code, notes, and snippets.

@rowandh
Created July 18, 2017 23:08
Show Gist options
  • Save rowandh/74942dfa1c9fd8bc26dbc2a56edf5dd8 to your computer and use it in GitHub Desktop.
Save rowandh/74942dfa1c9fd8bc26dbc2a56edf5dd8 to your computer and use it in GitHub Desktop.
NativeScript + Fresco example for downloading images with headers
if (applicationModule.android) {
applicationModule.on("launch", () => {
var fetcher = new NSNetworkFetcher();
var config = com.facebook.imagepipeline.core.ImagePipelineConfig
.newBuilder(application.android.context)
.setNetworkFetcher(fetcher)
.build();
com.facebook.drawee.backends.pipeline.Fresco.initialize(application.android.context, config);
});
}
export class NSFetchState extends com.facebook.imagepipeline.producers.FetchState
{
public submitTime: number;
public responseTime: number;
public fetchCompleteTime: number;
constructor(consumer, producerContext) {
super(consumer, producerContext);
return global.__native(this);
}
}
export class NSNetworkFetcher extends com.facebook.imagepipeline.producers.BaseNetworkFetcher {
constructor() {
super();
return global.__native(this);
}
createFetchState(consumer, context) {
return new NSFetchState(consumer, context);
}
fetch(fetchState, callback) {
var uri = fetchState.getUri();
fetchState.submitTime = android.os.SystemClock.elapsedRealtime();
try {
http.request({
url: uri.toString(),
method: "GET",
headers: {
"User-Agent": "NativeScript"
}
})
.then((response) => {
if (response.statusCode >= 200 && response.statusCode <= 300) {
console.log("Response length: " + response.content.raw.size() + " code : " + response.statusCode);
var inputStream = new java.io.ByteArrayInputStream(response.content.raw.toByteArray());
callback.onResponse(inputStream, response.content.raw.size());
} else {
callback.onFailure(new java.io.IOException("Request failed"));
}
})
.catch((e) => {
callback.onFailure(new java.io.IOException("Unknown error"))
});
} catch (e)
{
callback.onFailure(new java.io.IOException("Unknown error"));
}
}
onFetchCompletion(fetchState, byteSize) {
fetchState.fetchCompleteTime = android.os.SystemClock.elapsedRealtime();
}
getExtraMap() {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment