I am new to swift and I am trying the CoreML feature using React Native.
I have a source file with URL as string. I convert that string to URL using let imageURL = URL(fileURLWithPath: source) and I tried printing out the source which is of type string and it contains the absolutePath to the file file:///var/mobile/Containers/Data/Application/9C4D58FD-C817-47CB-A418-04BA30863C24/Library/Caches/Camera/133F8168-356A-436C-B7AF-557FA1C4F68F.jpg"
After that, I try to make the CIImage by using let image = CIImage.init(contentsOf: imageURL);
But when I try to print image, it returns nil. I searched a bit and tried using guard but no luck. Any help will be appreciated. Thanks in advance.
The CIImage does not create the image from a server URL. You can achieve this by first downloading the file at local location. And use the local file URL to create CIImage and then set it. The referred question/answer achieves the same, please check Loading/Downloading image from URL on Swift
If you still face issues do let me know. All the best!
Related
I am really confused of all the different possibilities Swift has to save data and retrieve data. Save and retrieve data through userDefaults is easy, but for storing a lot of images this is not the best way to do it. Then there is Core Data, which is I think to complicated to use for such a simple task. I continued to read about DocumentDirectory, I think this is a good way to save and retrieve data. However, all the tutorials are mostly from swift 2.0 and below, and I can not read that very well. Is the document directory the best way to store and retrieve images? I am making an online application which contains downloading images from users. However, the images are all the same from the same user, so I want to store the images offline to save some bandwidth.
I want to store and retrieve images with a path I can specify in a String. Every user has a unique identifier which I want to use as a path. How can I accomplish this?
Saving in your file system is definitely the best approach to use in this scenario.
Have a look to this answer:
https://stackoverflow.com/a/39896556/5109911
if let data = UIImageJPEGRepresentation(image, 0.8) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
where image is your UIImage
To Store Image in User default you can just simply create an extension of UI image view like 👇🏻 below Code Click the link to show code
https://i.stack.imgur.com/xEhcr.png
How to Use::- yourimageviewName.saveImage(),OtherImageViewName.loadImage()
https://i.stack.imgur.com/wcrNX.png
I am working against a REST API where you can make a call and then receive a image or pdf. I am using URLSession.shared.dataTask to make the call and when there is a image the call is a success (but it takes quite a long time, more then 5 seconds) and I can show the image in a UIImageView. But when there is a pdf, I don't know how to handle the result. The API returns the image / pdf as a ”filestream”.
When I print the data to the console it prints the size (bytes) and its the same size as in the server so in some way I have the correct data, I just don't know how to view the pdf.
I am using swift 3, iOS 10, xcode 8.
First of all you may want to ask your question into two part. Please edit it and ask the second part again.
There are two parts in this topic
1. Downloading the PDF and save it in File System
2. Get the pdf that saved in File System and read it using UIWebView or UIDocumentInteractionController
So, I will explain for the first one.
The first one can be done if you use REST HTTP client : Alamofire : Elegant HTTP Networking in Swift. So no need to use URLSession for such case and you will have to write so many lines if you do. It's simple and easy. So, I want you to try it. If you need URLSession instead, leave comment.
So how to download pdf using Alamofire :
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//.documentDirectory means it will store in Application Document Folder
let fileURL = documentsURL.appendPathComponent("data.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to: destination).response { response in
print(response)
if response.error == nil, let filePath = response.destinationURL?.path {
// do anything you want with filePath here.
// Here what you have to do Step 2. (Read the file that you downloaded)
}
}
This download procedure doesn't include requesting download link with encoded parameters. It was just simple way.
I need to read some metadata which can contain French or German characters & accents.
I think that I need to read the metadata as UTF8 String. But being a beginner in Swift and Apple in general I don't know how to do this.
I tried to implement some similar solutions found on stackOverflow but none worked.
What I'm working with:
let firstMeta: MPTimedMetadata = radioPlayer.timedMetadata.first as! MPTimedMetadata
let metaData = firstMeta.value as! String
print(metaData)
There I get
Antonin DvoÅák
instead of
Antonin Dvořák
Any ideas?
Easy solution for how to get UTF8 metadata from online audio stream using AVPlayer
https://stackoverflow.com/a/37831097/4249825
This is a problem in the library, you cannot fix it because the string is already decoded from data.
There is a reason why the whole set of classes was deprecated in iOS 9.
You should use AVPlayerViewController & AVPlayer & AVPlayerItem & AVMetadataItem.
They are solving this issue. Don't use MPMoviePlayerController.
let convertedString = String(data: metaData.dataUsingEncoding(NSISOLatin1StringEncoding)!, encoding: NSUTF8StringEncoding)!
I have this code in a new playground
import Foundation
let blogsURL: NSURL = NSURL(fileURLWithPath: "/Users/Francis/Documents/Xcode_projects/KM registratie/blogs.json")
let data = NSData(contentsOfURL: blogsURL)
On the second line the playground tells me that it (correctly) initialised the URL referring to file:///Users/Francis/Documents/Xcode_projects/KM%20registratie/blogs.json
and on the third line the playground tells me that data is nil
I already googled around but no question seems to be the exact same problem. I found this "NSData contentsOfURL constructor returns nil", but neither restarting Xcode nor restarting my entire computer fixes the problem.
playgrounds are sandboxed and it seems that there isn't an easy way to reach outside their "box". XML parsing in swift the title of this question is a bit misleading, the answer on it does answer this question
It's answered here:
XML parsing in swift
The problem is that your URL isn't pointing where you think it is. You're trying to open a URL in a subdirectory in your sandbox, and it doesn't exist.
You'll need to open the package contents of your playground (right click on the playground and select "Show Package Contents", add a folder called "Resources", and copy your file directly there.
Then you can get the file from the main bundle:
let url: NSURL! = NSBundle.mainBundle().URLForResource("blogs", withExtension: "json")
In my swift App, I need to convert Image as String, then I need to send to Server , i.e POST. Then, if I need to GET, I dont want to decode that. Response having Image file name and path.
ONline Converter:
If I convert the sample image through online converter, HERE. I am getting following string. If I pass this string to API, I can get image successfully.
Output:
iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR.... .....CIBhIIgQRCIIEQSCAQAgmEQAIhkEAIJBAIgQRCIIEQSCAEEgiEQAIhkEAIJCgN/F+AAQAXoGXl+IGgwwAAAABJRU5ErkJggg==
Through My Coding
If I convert the sample image through Coding, I am getting following string. If I pass this string to API, Successfully adding. But, I unable to view that image manually in browser too.
More Over,, Two Output Strings are not same. I dont know why? Kindly guide me, how to solve this?
Code:
var image : UIImage = UIImage(named: "home_recharge.png")!
var imageData = UIImagePNGRepresentation(image)
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
println("base64String \(base64String)")
Output:
iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAgAAAAAAAABIAAAAKAAAAEgAAABIAAAKygzM7MwAAAqWSURBVHgB7FwJ0JZDHC9yhJTkLuRMjuQ+opAr5zjGqAwZx...... .......FlIs5ASSDNQLA7EMtYMpBlICaQZKBYHYhlrBtIMpATSDBSLA7GMNQNpBlICaQaKxYFYxpqBNAMpgTQDxeJALGPNQJqBlECagWJxIJaxZiDNQP8B+6MkTad9NtcAAAAASUVORK5CYII=
You use png image representation but server saves the image with .jpg extension so browser tries to read image as JPEG file and fails.
You should replace UIImagePNGRepresentation with UIImageJPEGRepresentation or save image with .png extension.
The reason why browser can open online converter result image despite it has wrong extension is possibly that UIImagePNGRepresentation strips the image of its meta data and online converter not so browser can not figure the real type of image with wrong extension without meta data.