How to get the image url from RSS feed? - swift

I'm using an MWFeed (Objective-C feed parser from GitHub ) and I'm trying to access the image from the articles in my feed . So far I've wrote this :
let item = feedItems[indexPath.row] as MWFeedItem?
cell.itemImage?.layer.cornerRadius = 25.0
cell.titleLabel.text = item?.title
if item?.content != nil {
let htmlContent = item!.content as NSString
var imageSource = ""
let rangeOfString = NSMakeRange(0, htmlContent.length)
let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
if htmlContent.length > 0 {
let match = regex.firstMatch(in: htmlContent as String, options: [], range: rangeOfString)
if match != nil {
let imageURL = htmlContent.substring(with: match!.range(at: 2)) as NSString
if NSString(string: imageURL.lowercased).range(of: "feedburner").location == NSNotFound {
imageSource = imageURL as String
}
}
}
if imageSource != "" {
cell.itemImage?.sd_setImage(with: URL(string: imageSource), placeholderImage: UIImage(named: "Placeholder1"))
}
}
Edit : I've found out what is wrong , item.content is nil , so the code never gets called ,does anyone know why item.content = nil and how to solve it ?
This is the feed I'm using let url = NSURL(string: "https://sportingnews.com/rss")

Related

Get image thumbnails from Rumble?

I want to get a thumbnail image for videos from Rumble.
When getting images from Youtube I just do like this:
https://img.youtube.com/vi/f3ZccBBjmQg/0.jpg
Want to same from Rumble video url-
https://rumble.com/vxhedt-80000-matches-chain-reaction-domino-effect.html?mref=7ju1&mc=4w36m
I checked the rumble webpage of the link you provided. I am not sure if there is a smarter/faster way but here is a way to get the thumbnailUrl from their html code.
func getThumbnailFromRumble() {
let url = URL(string:"https://rumble.com/vxhedt-80000-matches-chain-reaction-domino-effect.html?mref=7ju1&mc=4w36m")!
URLSession.shared.dataTask(with: url){ data, response, error in
guard error == nil else { return }
guard let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data else {
return
}
let str = String(data: data, encoding: .utf8) // get the htm response as string
let prefix = "\"thumbnailUrl\":"
let suffix = ",\"uploadDate\""
let matches = str?.match("(\(prefix)(...*)\(suffix))")
if let thumbnailUrlMatch = matches?.first?.first {
let thumbnailUrl = thumbnailUrlMatch
.replacingOccurrences(of: prefix, with: "") // remove prefix from urlstring
.replacingOccurrences(of: suffix, with: "") // remove suffix from urlstring
.replacingOccurrences(of: "\"", with: "") // remove escaping characters from urlstring
if let url = URL(string: thumbnailUrl),
let data = try? Data(contentsOf: url) {
let uiImage = UIImage(data: data)
// use the uiimage
}
}
}.resume()
}
I use this extension to get the necessary string part from the html response
extension String {
func match(_ regex: String) -> [[String]] {
let nsString = self as NSString
return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)).map { match in
(0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
} ?? []
}
}
Feel free to improve the code.

Save (override) my jpg file with editing EXIF data

Im open and edit EXIF (or TIFF...) data in my jpg file.
Please help me save (override) my jpg file with editing data.
Working with this simple code:
let fileURL = URL(fileURLWithPath: "/Users/test/Pictures/IMG_2808.jpg")
if let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) {
var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
let exifDict = imageProperties?[kCGImagePropertyExifDictionary]
if let UserComment = exifDict?[kCGImagePropertyExifUserComment] ?? nil {
print("kCGImagePropertyExifUserComment: \(UserComment)")
}
else {
exifDict!.setValue("My comment...", forKey: kCGImagePropertyExifUserComment as String)
imageProperties![kCGImagePropertyExifDictionary] = exifDict
// What I should do in the next step for update and override my jpg file on disk?
// Maybe this is not nice way for this realisation? Please help
//
}
}
After some test Im found a solution:
let fileURL = URL(fileURLWithPath: "/Users/test/Pictures/IMG_2808.jpg")
if let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) {
var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
let exifDict = imageProperties?[kCGImagePropertyExifDictionary]
if let UserComment = exifDict?[kCGImagePropertyExifUserComment] ?? nil {
print("kCGImagePropertyExifUserComment: \(UserComment)")
}
else {
exifDict!.setValue("My comment...", forKey: kCGImagePropertyExifUserComment as String)
imageProperties![kCGImagePropertyExifDictionary] = exifDict
if let imageDestination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeJPEG, 1, nil) {
CGImageDestinationAddImageFromSource(imageDestination, imageSource, 0, imageProperties as CFDictionary?)
CGImageDestinationFinalize(imageDestination)
}
}
}
I don't know if this solution is true but it works!
Please comment if you know more perfected way

Callback function of requestExportSession is never called. Issue only happens on iOS 13

I have a problem when trying to get a video file from the user's device.
This is the function that worked on iOS 12 which seems correct to me. The requestExportSession function is being called but never executes the callback code. I'm using Swift 4.
private func getVideo(asset:AssetViewModel, completion: #escaping (contentData?) -> ()) {
guard let avAsset = asset.video else {completion(nil); return}
guard self.createTempDirectory() == true else {completion(nil); return}
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
let fileName = (avAsset as! AVURLAsset).url.lastPathComponent
let exportFileName = "\(asset.uuid).\(self.vidExt)"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("upload").appendingPathComponent(exportFileName)
var fileSize: Int = 0
var success:Bool = false
let videoGroup = DispatchGroup()
videoGroup.enter()
PHImageManager.default().requestExportSession(forVideo: asset.image, options: options, exportPreset: AVAssetExportPreset1280x720) { (exportSession, info) in
guard let exportSession = exportSession else {success = false; videoGroup.leave(); return}
exportSession.outputURL = fileURL
exportSession.outputFileType = AVFileType.mp4
exportSession.exportAsynchronously(completionHandler: {
if exportSession.status == AVAssetExportSessionStatus.completed {
let asset = AVURLAsset(url: fileURL)
fileSize = asset.fileSize ?? 0
success = true
videoGroup.leave()
}
})
}
videoGroup.wait()
if success {
completion(contentData(imageURL: fileURL, fileSize: fileSize, uuid: asset.uuid, fileName: fileName, ext: self.vidExt))
} else {
completion(nil)
}
}

How to pick GIF image from UIImagepicker in swift 4?

In my project trying to import GIF from UIImage picker. GIF image picked from gallery will certain actions like play and stop. Right now I can able to select GIF mage from gallery but result shows as image not gif image.
Can anyone help me out of this.
Try this it will help you.
Step1: Create a global variable
var IMG:String?
Step2: put this function in your code.
func getFileName(info: [String : Any]) -> String {
if let assetPath = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [assetPath], options: nil)
let asset = result.firstObject
let fileName = asset?.value(forKey: "filename")
let fileUrl = URL(string: fileName as! String)
if let name = fileUrl?.deletingPathExtension().lastPathComponent {
print(name)
//let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
if (assetPath.absoluteString.hasSuffix("JPG")) {
sonu = "JPG"
print("JPG")
}
else if (assetPath.absoluteString.hasSuffix("PNG")) {
sonu = "PNG"
print("PNG")
}
else if (assetPath.absoluteString.hasSuffix("GIF")) {
sonu = "GIF"
print("GIF")
}
else {
sonu = "Unknown"
print("Unknown")
}
return name
}
}
return ""
}
Step3: Set this code in your ImagePickerController
if let image = info[UIImagePickerControllerEditedImage] as? UIImage
{
imageview.image = image
let IMG = getFileName(info: info)
print(IMG)
if IMG == "JPG"
{
imageDataForApi = UIImagePNGRepresentation(image)
}
else if IMG == "GIF"
{
imageDataForApi = UIImageJPEGRepresentation(image, 0)
}
}
self.dismiss(animated: true) { () -> Void in
}

String(data: data, encoding: NSUTF8StringEncoding) return nil

I am using JSQMessage and pare to send and save video files
if (mediaType == kUTTypeVideo as String) || (mediaType == kUTTypeMovie as String) {
let movieURL = info[UIImagePickerControllerMediaURL] as? NSURL
let videoMediaItem = JSQVideoMediaItem.init(fileURL: movieURL, isReadyToPlay: true)
let message = JSQMessage(senderId: self.senderId, senderDisplayName: senderDisplayName, date: NSDate(), media: videoMediaItem)
self.saveMediaToParse(message, data: NSData(contentsOfURL: movieURL!)!, fileName:"videoFile")
self.messages += [message]
self.publishMessageToChannel(message)
self.finishSendingMessage()
}
func saveMediaToParse(message:JSQMessage, data:NSData, fileName:String) {
let imageFile = PFFile.init(data: data)
let msg = PFObject(className: "test")
msg["senderId"] = message.senderId
msg[fileName] = imageFile
msg["senderDisplayName"] = message.senderDisplayName
msg["user"] = PFUser.currentUser()
msg.saveInBackgroundWithBlock { (success, error) -> Void in
if(error != nil) {
NSLog("error: %#",(error?.localizedDescription)!)
}
}
}
when I am trying to get the video URL from the data as String I get back nil value. What am I doing wrong?
message["videoFile"].getDataInBackgroundWithBlock({ (data, error) -> Void in
if let data = data where error == nil {
**let dataStr = String(data: data, encoding: NSUTF8StringEncoding)**
let movieUrl = NSURL(string: dataStr!)
let videoMediaItem = JSQVideoMediaItem.init(fileURL: movieUrl, isReadyToPlay:true)
jsqMessage = JSQMessage(senderId:message["senderId"] as! String, displayName: message["senderDisplayName"] as! String, media: videoMediaItem)
self.messages.append(jsqMessage)
self.collectionView?.reloadData()
self.scrollToBottomAnimated(true)
}
})
}
self.messages.append(jsqMessage)
Ended up doing
let dataStr = NSTemporaryDirectory() + "temp.mov"
data.writeToFile(dataStr, atomically: true)
let movieUrl = NSURL(fileURLWithPath: dataStr)
Instead of
let dataStr = String(data: data, encoding: NSUTF8StringEncoding)**