How to load image from URL on watchos 2? - watchkit

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!

Related

fetch and retrieve data from firebase in swift

what I am trying to do is fetching data from firebase, but the data is nil because the user did not send his data to firebase yet, so when he enter the view controller that should show his data, the compiler make error. How can I solve this error? I tride to add alert, but it's still not working.
func getData(){
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("users")
.queryOrdered(byChild: "uid")
.queryEqual(toValue:userID)
.observe(.value) { (snapshot, error) in
if error == nil{// alert} elses{
if let data = snapshot.value as? NSDictionary {
if snapshot.exists() {
for a in ((snapshot.value as AnyObject).allKeys)!{
let users = data.value(forKey:a as! String) as! NSDictionary
let address = users.value(forKey:"Address") as! NSDictionary
self.lblAddressNickname.text = address.value(forKey:"addressNickname") as? String
}
}
}
}
}
}
So as of now i understand the question that you have problem in fetching data from firebase when no data is in the firebase and then alert will come and it will redirect to a new controller?
So based on my understanding i will give answer if any problem of understanding things then reply me?
first you have to check that particular user have any data in firebase database so if there is no data then alert function will call
if let data == data
{
fetch_logic is here
}
else
{
let alert = UIAlertController(title:"Add Data",message:"",preferredStyle: .alert)
let action = UIAlertAction(title: "Add Button", style: .default) { (UIAlertAction) in
}
alert.addAction(action)
present(alert,animation:true,completion:true)
}

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.
},

Meteor - Create a webhook

I'd like to implement a webhook with Meteor
I'm using the kadira/flowrouter Meteor plugin but no way to get POST data. Neither queryParams or params return the body of the message that I want to get.
FlowRouter.route('/my_weebhook', {
action: function(params, queryParams) {
console.log(queryParams);
console.log(params);
}
});
I do not know how to use kadira/flowrouter but you can use Meteor base package WebApp
to achieve what you need. Below is a sample code. You need to code or import something like this in your server.js
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import url from "url";
WebApp.connectHandlers.use('/my_webhook', (req, res) => {
//Below two lines show how you can parse the query string from url if you need to
const urlParts = url.parse(req.url, true);
const someVar = urlParts.query.someVar;
//Below code shows how to get the request body if you need
let body = "";
req.on('data', Meteor.bindEnvironment(function (data) {
body += data;
}));
req.on('end', Meteor.bindEnvironment(function () {
//You can access complete request body data in the variable body here.
console.log("body : ", body);
//write code to save body in db or do whatever you want to do with body.
}));
//Below you send response from your webhook listener
res.writeHead(200);
res.end("OK");
});

Firebase Storage: the uploaded image doesn't saved on the app

I upload the image via .Camera to Firebase Storage. When I closed app and run again, this image don't saved at my app. I know that I missed something. Please, tell me what I should to add. Thank's a lot!
This is my code:
import UIKit
import Firebase
import FirebaseStorage
class PicturesOfCoinsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBAction func saveButton(_ sender: UIButton) {
saveOneEuroCentImage()
}
#IBOutlet weak var oneEuroCentImage: UIImageView!
#IBAction func usePhotoButton(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
picker.delegate = self
}
func saveOneEuroCentImage() {
let storageRef = FIRStorage.storage().reference().child("userPictures/oneEuroCent.jpg")
if let uploadData = UIImagePNGRepresentation(self.oneEuroCentImage.image!) {
storageRef.put(uploadData, metadata: nil) {(metadata, error) in
if error != nil {
print(error)
return
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
oneEuroCentImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
picker.dismiss(animated: true, completion: nil)
}
}
If you want to have a persistent copy of the image on your app then you must save the photo to your apps document directory before the upload. From your code above you are only uploading it to your cloud storage in firebase but there is no code for saving your picture locally, thats why it does not exist when the app is run again.
I suggest you create a documents directory file path or url for the image and then save it.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let path = paths.first
let imageFolderPath = path?.appending("MyFBImages")
if !FileManager.default.fileExists(atPath: imageFolderPath!){
do {
try FileManager.default.createDirectory(atPath: imageFolderPath!, withIntermediateDirectories: true, attributes: [:])
} catch let error {
print(error.localizedDescription)
}
}
let imageFilePath = imageFolderPath?.appending("myImageName.jpg")
let imageData = UIImageJPEGRepresentation(UIImage(), 1)
do {
try imageData?.write(to: URL(fileURLWithPath: imageFilePath!))
} catch let error {
print(error.localizedDescription)
}
N/B : the imageData in the code you can get that from the image you created just before the upload to firebase.
This should help you save your image locally. Next time you run your app you can access your previous images by initializing UIImage from contents of the url that holds your saved photos.
I hope this helps you out.

Trouble uploading videos from iOS using WordPress REST api

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.

Resources