Trouble uploading videos from iOS using WordPress REST api - wordpress

I am very new at this, so sorry if I have missed something.
I am trying to upload a video from iOS to WordPress using the WP REST API and Alamofire.
Some videos will upload just fine while other videos get a rest_upload_no_content_disposition status = 400 error.
Here is my code to uploading a video
class func pageVideo(accessToken:String, filePath:NSURL, completion: AnyObject? -> Void) {
let endpoint = "http://XXXXXXXXX.com/wp-json/wp/v2/media/?access_token=\(accessToken)"
let parameters = [
"Content-Type": "multipart/form-data",
"Content-Disposition": "attachment; filename=appVideo.mov",
"media_type": "file"
]
var fileData : NSData?
if let fileContents = NSFileManager.defaultManager().contentsAtPath(filePath.path!) {
fileData = fileContents
}
let mgr = Alamofire.Manager.sharedInstance
mgr.upload(.POST, endpoint, multipartFormData: { multipartFormData in
if let _fileData = fileData {
multipartFormData.appendBodyPart(data: _fileData, name: "file", fileName: "file.mov", mimeType: "file/mov")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.response {(request, response, data, error ) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
if let dict = json as? NSDictionary{
if let url = dict.valueForKeyPath("source_url") as? String{
completion(url)
}
}
} catch let error as NSError{
// completion(error.localizedDescription)
print(error.localizedDescription)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
}
It seems like shorter videos work while anything over 30 seconds fails.
Even shorter videos that do upload take a very long time.
Any help would be greatly appreciated.

Nothing was wrong with my code I just needed to compress the videos. the longer videos were hitting the WordPress upload limit. Also it's always a good idea to compress videos or images that your uploading somewhere.

Related

LinkedIn API: upload video returns 500

According to the LinkedIn API documentation, I'm trying to push video. Unfortunately, I get a 500 error without any details when I'm running PUT request with the binary video file on the given endpoint from initialization request.
My video fit with video specifications.
Did I miss something ?
i have been in the same situation as you few days ago.
the solution is :
if your file is more then 4MB you must divide your file.
and in the initialize upload you will get a list of uploadUrls. so use each link with parts of file.
Thanks #ARGOUBI Sofien for your answer. I found my mistake: the fileSizeBytes value was wrong and gave me only one link for the upload. With the good value, I have several endpoints.
So, I'm initializing upload with that body:
{
"initializeUploadRequest": {
"owner": "urn:li:organization:MY_ID",
"fileSizeBytes": 10903312,
"uploadCaptions": false,
"uploadThumbnail": true
}
}
I got this response:
{
"value": {
"uploadUrlsExpireAt": 1657618793558,
"video": "urn:li:video:C4E10AQEDRhUsYL99HQ",
"uploadInstructions": [
{
"uploadUrl": "https://www.linkedin.com/dms-uploads/C4E10AQEDRhUsYL99HQ/uploadedVideo?sau=aHR0cHM6Ly93d3[...]t3yak1",
"lastByte": 4194303,
"firstByte": 0
},
{
"uploadUrl": "https://www.linkedin.com/dms-uploads/C4E10AQEDRhUsYL99HQ/uploadedVideo?sau=aHR0cHM6Ly93d3cub[...]f13yak1",
"lastByte": 8388607,
"firstByte": 4194304
},
{
"uploadUrl": "https://www.linkedin.com/dms-uploads/C4E10AQEDRhUsYL99HQ/uploadedVideo?sau=aHR0cHM6Ly93d3cubGlua2V[...]V3yak1",
"lastByte": 10903311,
"firstByte": 8388608
}
],
"uploadToken": "",
"thumbnailUploadUrl": "https://www.linkedin.com/dms-uploads/C4E10AQEDRhUsYL9[...]mF3yak1"
}
}
It's look like better ✌️
EDIT
After several tests, the upload is ok when I have only one upload links but I does not get any response from the server when I have several upload URL.
My code:
const uploadPromises: Array<() => Promise<AxiosResponse<void>>> = [];
uploadData.data.value.uploadInstructions.map((uploadInstruction: UploadInstructionType) => {
const bufferChunk: Buffer = videoStream.data.subarray(uploadInstruction.firstByte, uploadInstruction.lastByte + 1);
const func = async (): Promise<AxiosResponse<void>> => linkedinRestApiRepository.uploadMedia(uploadInstruction.uploadUrl, bufferChunk, videoContentType, videoContentLength);
uploadPromises.push(func);
});
let uploadVideoResponses: Array<AxiosResponse<void>>;
try {
uploadVideoResponses = await series(uploadPromises);
} catch (e) {
console.error(e);
}
Something is wrong we I have several upload links but I does not know what 😞
in my case i have divide my file buffer into arrayBuffer
then you can use map to upload each buffer with the right urlUpload

Firebase Dynamic Link pass custom parameters to iOS and android

I have a custom function in python to build the dynamic link:
def generate_dynamic_link(link, title=None, image=None, description=None, short=True, timeout=10):
api_url = FIREBASE_DYNAMIC_LINK_API_URL
domain = DYNAMIC_LINK_DOMAIN
apn = APP_APN
isi = APP_ISI
ibi = APP_IBI
payload = {
"dynamicLinkInfo": {
"domainUriPrefix": domain,
"link": link,
"androidInfo": {
"androidPackageName": apn,
},
"iosInfo": {
"iosBundleId": ibi,
"iosAppStoreId": isi
},
"socialMetaTagInfo": {
"socialTitle": title,
"socialDescription": description,
"socialImageLink": image
}
},
"suffix": {
"option": "SHORT" if short else "UNGUESSABLE"
}
response = requests.post(api_url, json=payload, timeout=timeout)
data = response.json()
if not response.ok:
raise Exception(data)
return data['shortLink']
I want to pass two parameters to the android and ios app. How can I Do that?
Example:
?type=user&username=testuser
I wrote my first Medium article about this (it’s not a great tutorial) but it shows how to do this. You are correct with how you pass data using ?yourDataHere at the end of your link.
https://augustkimo.medium.com/simple-flutter-sharing-and-deeplinking-open-apps-from-a-url-be56613bdbe6
Then you can handle the deep links by calling the function below. Pretty much you can get the link used to open the app, then get the data from that URL/link string
//ADD THIS FUNCTION TO HANDLE DEEP LINKS
Future<Null> initUniLinks()async{
try{
Uri initialLink = await getInitialUri();
print(initialLink);
var dataFromLink = initialLink.toString().split(β€˜?’)[1];
print(dataFromLink);
} on PlatformException {
print('platfrom exception unilink');
}
}

How can you add a custom image to a notification in iOS with react-native-firebase

I want to use the data payload in a firebase cloud messaging to present an image in the notification. The image is specified as an url to a website where the image is hosted.
It appears as what I want to do is to add the image as an attachment, see row 8 below. There are however no image present, other than the application icon.
const notification = new firebase.notifications.Notification()
.setNotificationId("notification_id")
.setTitle(notification.data.title)
.setBody(notification.data.body)
.setData({ url: notification.data.url })
.ios.setLaunchImage(notification.data.icon)
.android.setBigPicture(notification.data.icon)
.ios.addAttachment("some_id", notification.data.icon, {});
The problem is that there are no error messages that can help me. The notification displays with the title and body as expected, but no image is present. From what I can read of the documentation what I want to do is possible.
The short answer is that react-native on iOS does not support "rich push notifications" i.e. notifications with images.
The longer answer is that it is rather simple to add support for an image to a react-native project if you add a little swift code.
Work around:
Open your xcode project and go to "editor"->"Add Target...". Select the "Application Extension" named "Notification Service Extension".
You can name it whatever you want but make sure that the correct project is selected if you are using CocoaPods.
Once it is created replace the content of override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) with:
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
// get the variables that is needed later.
guard let bestAttemptContent = bestAttemptContent,
let attachmentURLAsString = bestAttemptContent.userInfo["icon"] as? String,
// "icon" is the key for the image url in the notification. It
// could be named whatever you want.
let attachmentURL = URL(string: attachmentURLAsString) else {
return
}
// call a custom function to download the image before attaching
// it to the notification and presenting it.
downloadImageFrom(url: attachmentURL) { (attachment) in
if let attachment = attachment {
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}
}
Then the downloadImageFrom function needs to be created:
private func downloadImageFrom(url: URL, with completionHandler: #escaping (UNNotificationAttachment?) -> Void) {
let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, response, error) in
//verify that a url exists.
guard let downloadedUrl = downloadedUrl else {
completionHandler(nil)
return
}
// create a local unique filepath.
var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
let uniqueURLEnding = ProcessInfo.processInfo.globallyUniqueString + ".png"
urlPath = urlPath.appendingPathComponent(uniqueURLEnding)
// fetch the image from the url
try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)
// if successful, return the image as an attachment.
do {
let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
completionHandler(attachment)
} catch {
completionHandler(nil)
}
}
task.resume()
}
When you build the application it will use this code instead for loading notifications.
When sending the notification you have to remember to include the "icon" value. An example of what is needed to send a notification:
"notification": {
"body": "body",
"title": "title"
"mutable_content": true // this row is required for the notification to work!
},
"data": {
"icon":"https://pusher.com/static_logos/320x320.png", // change to your image url.
},

Making http Post request on Gupshup IDE works?

I copied gupshup's document code and modified just url as "http://posttestserver.com/post.php" and it doesn't work.
Anyone has an advice for me?
else if(event.message.toLowerCase() == "post") {
var contextParam = {
"User": {
"userName": "sbCobxxxx",
"Password": "xxxxxxx-9f-4307-9d9a-451f3xxxx075",
"Pin": "16776"
}
};
var url = "http://posttestserver.com/post.php";
var param = JSON.stringify(contextParam);
var header = {"Content-Type": "application/json"};
context.simplehttp.makePost(url, param, header);
}
function HttpResponseHandler(context, event) {
// if(event.geturl === "http://ip-api.com/json")
context.sendResponse(event.getresp);
}
Response returns empty string: ""
Thanks in advance.
Are you testing using Gupshup's emulator? If yes then POST and GET calls with headers and params doesn't work in the emulator as of now. The documentations mentions it. However, you can deploy the code and test it out using Gupshup proxy bot on Facebook messenger and it will work fine.
Here is a screenshot of the testing I did after directly copying your code into the IDE.

How to load image from URL on watchos 2?

Is there any framework can be used to load an image from URL in watchos 2 ? I tried SDWebImage but it doesn't support watchos2?
Its no framwork, but I've written this extension:
extension WKInterfaceImage {
public func imageFromUrl(_ urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(url: url as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let imageData = data as Data? {
DispatchQueue.main.async {
self.setImageData(imageData)
}
}
});
task.resume()
}
}
}
Just add a WKInterfaceImage to your watchOS storyboard, attach it and then call
imageView.imageFromUrl("https://something")
Let me know if it works!

Resources