Swift 3: How to display an image using URL with API [duplicate] - swift

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I tried to show an image but the following error occurs:
error : fatal error: unexpectedly found nil while unwrapping an
Optional value
var imageURL:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
let data = NSData(contentsOfURL:url!)
if data!= nil {
imageURL.image = UIImage(data:data!)
}
}

From apples docs:
Important
Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.
Maybe consider using Alamofire for this task?
Alamofire.request(.GET, "http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg").response { (request, response, data, error) in
self.imageURL.image = UIImage(data: data, scale:1)
}

Related

UIDocumentPicker function for under IOS.14

I'm beginner in Swift. I have made a document picker at my task. But I see the documentation it was deprecated to used open var documentPickerMode: UIDocumentPickerMode { get }. While the project in my task runs with minimum deployment of IOS13.
Is there a solution for this feature that can be used on IOS14 and below? Or is this normal, where users need to update IOS?. Forgive me for my ignorance, as I'm new to swift world.
If you look at the docs:
https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller
...you'll see the list of four initializers introduced in iOS 14. Each one configures the picker for one specific type of task. There is no need for a "mode" because you cannot not know how your picker is configured, because you configured it. That is the modern architecture.
At the bottom of the same page you will see the three deprecated initializers from iOS 13 and before, each of which takes a "mode" as a parameter. That is what you must use if you insist upon supporting iOS 13, even though they are deprecated in later systems. And that's fine. "Deprecated" means discouraged and superseded; it does not mean illegal. What you're getting is just a warning, not (as your title wrongly stated) an error.
just try this one code
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
guard url.startAccessingSecurityScopedResource() else {
return
}
defer { url.stopAccessingSecurityScopedResource() }
var error: NSError? = nil
NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in
let _ : [URLResourceKey] = [.nameKey, .isDirectoryKey]
let documentFileData = NSData(contentsOf: (url)) as Data?
pickImageCallback?(nil, url.lastPathComponent, documentFileData)
}
}

Extra argument in call when calling JSONSerialization.JSONObjectWithData [duplicate]

This question already has answers here:
Swift: Extra argument 'error' in call
(3 answers)
Closed 4 years ago.
let data = json.data(using: String.Encoding.utf8)!
let wrapper = JSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as NSDictionary
Error is thrown on this line
let wrapper = JSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as NSDictionary
what do i do?
Remove the extra argument. The Swift version of the method is declared like this:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
As you can see, it throws an error instead of taking an error parameter. There's even a sidebar in the documentation labeled Handling Errors in Swift: that explains a bit about how to use this method with try/catch to handle errors, and there's a link to more information on the topic.

crashing found nil while unwrapping optional value [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
Hi all I'm creating a chat app, using firebase.
when I get to the screen to create a channel it crashes saying found nil while unwrapping optional value. If i go back into the app the channel has been created so i presume it is finding nil when changing viewcontrolers and there must be nothing in the database for the new channel under messages. below is the code and where it crashes.
var channelRef: FIRDatabaseReference?
private lazy var messageRef: FIRDatabaseReference = self.channelRef!.child("messages")
then it crashes here...
private func observeMessages() {
messageRef = channelRef!.child("messages")
this function is called on view did load
Instead of force unwraps you should use and if let like this:
if let channelRef = channelRef {
messageRef = channelRef.child("messages")
} //maybe add an else and do some logic if value is not there
Or you could declare var channelRef: FIRDatabaseReference! if you expect it to always be there and be of this type

Swift : Unexpectedly found nil [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Fatal error: unexpectedly found nil while unwrapping an Optional values [duplicate]
(13 answers)
Closed 6 years ago.
This code is causing my application to crash and I can't figure out a way to fix it. The error is : fatal error: unexpectedly found nil while unwrapping an Optional value
Any idea how I can fix it? The two lines I'm returning in my createCharacters() function is whats causing the crash:
class NACharacters {
var featuredImage : UIImage!
init(featuredImage: UIImage){
self.featuredImage = featuredImage
}
static func createCharacters() -> [NACharacters]{
return[
//THE TWO LINES BELOW CAUSE THE CRASH
NACharacters(featuredImage: UIImage(named: "Diplo Squad")!),
NACharacters(featuredImage: UIImage(named: "StopIcon")!)
]
}
}
Solution: I simply needed to delete the space between "Diplo" and "Squad". It seems this was returning nil.
check if your images "Diplo Squad" und "StopIcon" exist.
(You may need to remove the space in the first image name)
At least one of these UIImage(name: "...") calls returns nil and that's probably the crash reason.
The only thing that could be nil lines are in the UIImages. check that they exist in your projectNavigator or assets.

NSURLSession crashing from Swift

I've got a simple class that uses an NSURLSession.
class test {
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration());
func f() {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0), { () -> Void in
var task = self.session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
// cry
return;
}
var error: NSError? = nil;
var dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as! Dictionary<String, String>;
// use dict
});
task.resume();
});
}
When I try to deserialize the data as JSON, the application crashes.
I've determined that the data seems to be of the right length but the content looks like garbage in the debugger, so it seems to me that the data object passed in is broken. Furthermore, I suspect some stack smashing as I can step through this completion handler and see that it's the attempt to deserialize the data that's crashing, but when the actual crash occurs, the stack in the debugger mentions nothing about the completion handler or any of my code.
I've seen several samples of using NSURLSession that look pretty much exactly like mine that just work. I tried using the shared session instead of making a new one, but that did not help either.
What is causing this crash?
Seems that the JSON was not actually all strings- I brainfarted and one of them was actually a number.
The real problem in the question is that Swift is completely worthless when handling the problem of force casts failing. Not only do you not get any kind of useful error at runtime that you could handle or recover from, but the debugging information presented when it occurs is completely misleading and points to totally the wrong place. You simply get a trap in a function without symbols with the wrong callstack.