print command paints green in debug area in Xcode - ios

I'm facing weird issue. The print command in following code paints green area in debug window in xCode. It's random.
Why is it happening? How to fix it?
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completionHandler(nil, error)
}
return
}
print("############## Data ############################################################")
if let str = String(data: data, encoding: .utf8) { print(str) }
print("################################################################################")
}

The fix turn out to be the same age old trick, reboot the system. macOS has been crashing all day today when I use Xcode.

Restart did not help me.
Making Xcode go to fullscreen made it disappear, and was able to return back to non-fullscreen with it still not green.

Related

phResourceManager.writeData(for... wont run on iOS 14

Before I updated to iOS 14 on my iPhone, this code was working perfectly. After, iOS 14 this is weirdly not running... it is very odd and I have not seen any solution online, additionally from my investigation, I have not been able to see any change.
This code is used in order to retrieve a videoURL for this video from the imported Camera Roll (I use import Photos...).
phResourceManager.writeData(for: resource.last!, toFile: newURL!, options: resourceRequestOptions) { (error) in
if error != nil {
print(error, "not c67omplted error?")
} else {
print("woah completedd 345?")
newUserTakenVideo.videoURL = newURL
print(newUserTakenVideo.videoURL, "<--?")
}
}
EDIT:
To be clear, it "does not run" means the compleition block never runs... as in it never even runs and gives an error, the compleition block simply never is called (nothing prints at least..)
And here is a print statement printing out all the values I pass in to the parameters:
phResourceManager:
<PHAssetResourceManager: 0x282d352c0>
resource.last:
Optional(<PHAssetResource: 0x28128bc00> {
type: video
uti: public.mpeg-4
filename: v07044090000bu6n1nhlp4leque7r720.mp4
asset: C97B45D3-7039-4626-BA3E-BCA67912A2A9/L0/001
locallyAvailable: YES
fileURL: file:///var/mobile/Media/DCIM/113APPLE/IMG_3404.MP4
width: 576
height: 1024
fileSize: 4664955
analysisType: unavailable
cplResourceType: Original
isCurrent: YES
})
newURL:
Optional(file:///var/mobile/Containers/Data/Application/E2792F47-142E-4601-8D5B-F549D03C9AFE/Documents/Untitled%2027228354.MP4)
resourceRequestOptions:
<PHAssetResourceRequestOptions: 0x28230d480>
Note: this is the decleration for the resource variable:
let resource = PHAssetResource.assetResources(for: (cell?.assetPH)!)
I have a solution to this! Swift 4+, tested on iOS 14!
I looked through using a PHAssetResourceRequest, but the file names were messed with in the process, and it generally didn't work with my sandbox. Then I also tried requesting a AVPlayerItem from the PHAsset but this too, did not work with sandboxing...
But then, I tried simply using PHAssetResourceManager.default().writeData(... and seemingly started working!
I tested a bit more and seemed to work, here is the full code:
let resource = PHAssetResource.assetResources(for: (cell?.assetPH)!)
let resourceRequestOptions = PHAssetResourceRequestOptions()
let newURL = ExistingMediaVC.newFileUrl
PHAssetResourceManager.default().writeData(for: resource.last!, toFile: newURL!, options: resourceRequestOptions) { (error) in
if error != nil {
print(error, "error")
} else {
print("good")
newUserTakenVideo.videoURL = newURL
}
}
It is quite simple!! Tell me if anything is not working, and note I still use the ExisitingMedia.fileURL variable you used in your original code as well :)

Presentation is in process issue following Error

I am playing with Vision for text recognition, I present the camera, take a photo and the text is detected and processed...running very well. The issue I have is when there is no text in the photo, I get an error from VNImageRequestHandler, which is fine, but the issue is that I can't re-open the camera, I get "Warning: Attempt to present UIImagePickerController: ... while a presentation is in progress!.
here is some code where I process the image looking for some text...
guard let image = image, let cgImage = image.cgImage else { return }
let requests = [textDetectionRequest]
let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: .up, options: [:] )
DispatchQueue.global(qos: .userInitiated).async {
do {
try imageRequestHandler.perform(requests)
} catch let error {
print("Error: \(error)")
}
}
}
the Error is
"Error: Error Domain=com.apple.vis Code=11 "encountered unknown
exception" UserInfo={NSLocalizedDescription=encountered unknown
exception}"
which is fine, I just want to be able to open the UIImagePickerController after that Error.
I have tried to dismiss the UIImagePickerController, does not work... and I can't find what presentation is really in process.
Thanks.
For me it was something completely unrelated that caused this error. After the VNRequestCompletionHandler was called, I attempted to initialize a malformed NSPredicate. Then I would get the error that you described. Fixing the predicate also fixed the issue you described.
I would look to see if there's any work you're doing after the completion handler is called that can throw an error and fix that.

Drag and Drop from Files app fails with 257 file protection error

I've got Drag and Drop working (iOS 11) for Safari / Mail etc, however when I try and drag & drop an image from my iCloud Desktop (using the Files app), I get a couldn’t be opened because you don’t have permission to view it error.
I thought Drag & Drop deals with file protection issues in the background at 'drop' time. How can I access a file I'm trying to share with my app explicitly? Here's the code that fails
itemProvider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil, completionHandler: { item, error in
var data: Data? = nil
if item != nil && (item is URL) {
if let item = item as? URL {
do {
data = try Data(contentsOf: item) // <--- fails
} catch {
print(error.localizedDescription)
}
}
}
}
Do.. had to wrap it around
item.startAccessingSecurityScopedResource()
and
item.stopAccessingSecurityScopedResource()

Application communicates with database on iOS simulator but not on device

Good evening,
I have a table view that gets populated with data from my local MySQL database. I'm using MAMP along with PHPmyadmin.
It works perfectly fine on the simulator, as you can see:
Working Database
However, when I try to run it on my iPhone device, it doesn't load anything:
Not working Database
What could be the cause for that? I don't really get the difference between the simulator and the device.
The code looks like this:
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
It prints "Data Downloaded" when on simulator and "Failed to download data" on the device.
I'm using Xcode 9 and Swift 4.
Thanks a lot for your help

Swift 3 - How to handle URLRequest / URLSession errors?

I want to know how you guys handle errors when using a URLRequest in your app. How do you go about notifying your users that an error has occurred? Do you even notify your users at all? Do you try and reload the URLRequest again? Do you tell your users to close the current screen and open it again with an alert box? I have no clue.
Once there's an error, your app stops. So what do you do when this happens and you have a network issue, bad Json data?
What do you do when you get a "Bad Network Connection (The server is down)" or the URLSession comes back with an error and the internet connection is fine?
Please look at the code below and help me figure out what needs to be done when an error occurs.
let url = URL(string:"http://example/jsonFile.php")
var request = URLRequest(url:url!)
request.httpMethod = "POST"
let postingString = "id=\(id)"
request.httpBody = postingString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){(data, response, error) -> Void in
if error != nil {
print("error \(error)")
// *****
// What do you do here? Do you tell your users anything?
// *****
return
}
// Check for Error
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: .allowFragments) as! [String: AnyObject]
print("jsonResult \(jsonResult)")
}
catch{
print("JSON serialization failed")
// *****
// What do you do here? Do you tell your users anything?
// *****
}
}
}
task.resume()
It is often a bad idea to hide the errors and do nothing (see Error Hiding Anti-Pattern). Unfortunately, handling errors is not easy and can be tedious some times. Pretty code examples quickly become "uglier" when exceptions and errors have to be handled. It takes time to learn to do it well.
In the case of network connections, you would want to wrap your requests into asynchronous methods that take a completion callback as parameter. This callback will often receive a successful result or an error, sometimes wrapped in an enum to remove ambiguity (see Result as an example).
Once you know a network request has failed, you can present that information to the user in a clean, informational but non-obstructive way. To find out what other applications do in this scenario, turn on Airplane Mode in your phone and poke around.
Here are some examples:
Apple Music
Facebook Messenger

Resources