PFQuery *queryBankList = [PFQuery queryWithClassName:#"Blood_Bank_Master"];
[queryBankList findObjectsInBackgroundWithBlock:^(NSArray *BankObjects, NSError *error)
{
if (!error)
{
[aBankInfo addObjectsFromArray:BankObjects];
} else
{
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
Edit :
for some reason i believe you spell wrong the class name .
are you sure that your class name is Blood_Bank_Master ?
if not you can check by adding those lines
NSLog(#" my bank objects %#",BankObjects ) then post what you see in the output.
Related
I want to track additional information about errors to help support issues and be proactive where errors/bugs are encountered. I am new to iOS/Swift, but I have followed a few YouTube videos and posts on error handling to alert users of an error (this was the most up to date/best one I found) but I also want to provide more detail as well to help support. I created a custom error:
enum CustomError: Error {
case apiDecodingError
...
}
and extended it:
extension CustomError: LocalizedError {
var errorDescription: String? {
switch self {
case .apiDecodingError:
return NSLocalizedString("Problem understanding service response.", comment: "")
...
}
}
}
but I cannot add additional properties to the extension because: Extensions must not contain stored properties.
When I catch and throw a custom error from, for example, decoding the response of an api call:
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
throw CustomError.DecodingError
This makes for a simplified user message:
but I also want to send the detail to the bug tracking system with the specific problem, such as the key which was having the problem.
} catch {
print("\(error)")
let properties = ["Error" : error.localizedDescription]
Analytics.trackEvent("UpdateNotificationSetting", withProperties: properties, flags: .critical)
isAlertErrorPresented = true
errorAlert = ErrorAlert(error: error)
}
I would like to send along the detail but that means the custom error needs additional information from the inner error. I'm a novice at SwiftUI, is there a standard way to address this?
You can do it by expanding CustomError
enum CustomError: LocalizedError{
///Takes in any error and makes it compatible with `LocalizedError`
case error(Error)
///Allows for throwing an error with a custom description
case custom(description: String, failureReason: String? = nil, helpAnchor: String? = nil, recoverySuggestion: String? = nil)
///Can be used as a custom key using localization features
case customKey
///Mimic your decoding error
case apiDecodingError(key: String, path: String)
var errorDescription: String?{
switch self{
case .error(let error):
return error.localizedDescription
case .custom(let description, _ , _, _):
return description
case .apiDecodingError(let key, path: let path):
return String(format: "Key %# not found: codingPath: %#", key, path)
default:
///Add `customKeyErrorDescription` to Localizable.strings
return NSLocalizedString("\(self)" + "ErrorDescription", comment: "AppError")
}
}
var failureReason: String?{
switch self{
case .error(let error):
let nsError = error as NSError
return nsError.localizedFailureReason
case .custom(_ , let failureReason , _, _):
return failureReason
case .apiDecodingError(_, _):
return nil
default:
///Add `customKeyFailureReason` to Localizable.strings
return NSLocalizedString("\(self)" + "FailureReason", comment: "AppError")
}
}
var helpAnchor: String?{
switch self{
case .error(let error):
let nsError = error as NSError
return nsError.helpAnchor
case .custom(_ , _ , let helpAnchor, _):
return helpAnchor
case .apiDecodingError(_, _):
return nil
default:
///Add `customKeyHelpAnchor` to Localizable.strings
return NSLocalizedString("\(self)" + "HelpAnchor", comment: "AppError")
}
}
var recoverySuggestion: String?{
switch self{
case .error(let error):
let nsError = error as NSError
return nsError.localizedRecoverySuggestion
case .custom(_, _ , _, let recoverySuggestion):
return recoverySuggestion
case .apiDecodingError(_, _):
return nil
default:
///Add `customKeyRecoverySuggestion` to Localizable.strings
return NSLocalizedString("\(self)" + "RecoverySuggestion", comment: "AppError")
}
}
}
Then you can pass along any standard error
do{
}catch{
CustomError.error(error)
}
My project had been getting the URL string for the medium sized profile pic using this code:
let downloadMediumPicTask = session.dataTask(with: mediumProfPictureURL) { (data, response, error)
in
// The download has finished.
if let e2 = error {
print("Error downloading profile picture: \(e2)")
} else {
if let res2 = response as? HTTPURLResponse {
print("Downloaded medium profile picture with response code \(res2.statusCode)")
if let imageData2 = data {
mediumProfilePictureUIImageFile = UIImage(data: imageData2)!
print("mediumProfilePictureUIImageFile has now been defined as: \(mediumProfilePictureUIImageFile).")
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadMediumPicTask.resume()
It crashes here giving a 403 response code. The URL that is being referenced is an expired signature URL from Facebook. Firebase doesn't adjust to get the new appropriate URL, and it was from Firebase that I had been getting the URL. I can't figure out how to get it directly as tried below:
func getUrlOfMediumProfilePic(){
if (FBSDKAccessToken.current() != nil) {
let graphPathPart2 = "me/picture"
let paramsPart2 = ["type":"medium", "redirect":"false"]
let completionHandlerPart2 = { (connection: FBSDKGraphRequestConnection?, result: Any?, error: Error?) in
if let error = error {
print("Medium picture graph call contained an error: \(error.localizedDescription)")
return
} else {
guard connection != nil else {
print("getURLOfLargeProfilePic() function aborted bc connection failed.")
return
}
let results = result! as! NSDictionary
let dataDict = results["data"] as! NSDictionary
stringOfMediumProfilePicURLaka100x100 = dataDict["url"] as! String
print("medium picture graph call results define stringOfMediumProfilePicURLaka100x100 as: \(stringOfMediumProfilePicURLaka100x100)")
}
}
let graphRequest = FBSDKGraphRequest(graphPath: graphPathPart2, parameters: paramsPart2)!
graphRequest.start(completionHandler: completionHandlerPart2)
}else{
print("User not logged in when getURLOfMediumProfilePic() function was run.")
return
}
}
This code yields an error with code 8.
Have you tried this:
https://graph.facebook.com/{id}/picture?width=100&height=100
I don't know swift, so I can't help about syntax. I think you can make http request to url and get image.
Hope this help :)
I have old code:
func htmlToText(encodedString:String) -> String?
{
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
do
{
return try NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil).string
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
and I want to translate it to swift 3, now i have:
let encodedData = encodedString.data(using: String.Encoding.utf8)!
do
{
return try NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil).string
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
This code generate error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x608000251d30'
I have no idea what could went wrong. Can anybody help me?
String.Encoding is a Swift struct, which cannot be passed to Objective-C world. When Swift find such things in Any, it generates _SwiftValue which is completely useless in Objective-C.
Try this:
return try NSAttributedString(data: encodedData, options: [
NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:String.Encoding.utf8.rawValue
], documentAttributes: nil).string
I've written an application that downloads images from a website.
If this image already exists on the device I'm trying to replace it.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let userId = Int.init(downloadTask.taskDescription!)! // task description is definetly set in downloadImage() and is an Int
guard let target = imageFolder?.appendingPathComponent("\(userId).jpg") else {
delegate?.imageDownloadFailed(forUser: userId, error: "Could not create target URL.")
return
}
do {
if fileManager.fileExists(atPath: target.path) {
_ = try fileManager.replaceItemAt(target, withItemAt: location)
} else {
try fileManager.moveItem(at: location, to: target)
}
delegate?.savedImage(forUser: userId, at: target)
} catch let error {
delegate?.imageDownloadFailed(forUser: userId, error: error.localizedDescription)
}
}
The problem occurs in the if-statement:
_ = try fileManager.replaceItemAt(target, withItemAt: location)
I always got EXC_BAD_ACCESS and I can't find the error.
fileManager, target, and location are non-nil.
I've already tried to dispatch the code synchronous to the main thread, but the error still persists.
Any advices?
Edit:
Since I'm not the only one who got this error I decided to create a bug report at Apple.
The report is available at Open Radar; click
I've also uploaded a playground file at pastebin.com which demonstrates the error and provides a quick solution similar to the one of naudec.
Had the same issue. Ended up writing my own version:
let fileManager = FileManager.default
func copyItem(at srcURL: URL, to dstURL: URL) {
do {
try fileManager.copyItem(at: srcURL, to: dstURL)
} catch let error as NSError {
if error.code == NSFileWriteFileExistsError {
print("File exists. Trying to replace")
replaceItem(at: dstURL, with: srcURL)
}
}
}
func replaceItem(at dstURL: URL, with srcURL: URL) {
do {
try fileManager.removeItem(at: dstURL)
copyItem(at: srcURL, to: dstURL)
} catch let error as NSError {
print(error.localizedDescription)
}
}
I call copyItem first.
The class holding this method does not exist any more at the time your download finishes and did release your filemanager. Create the FileManager within your completion closure:
...
let localFilemanager = FileManager.default
do {
...
When I am Fetching name and pic_square from my friend list the it shows the following error.
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
FBSDKLog: Error: HTTP status code: 400
FBSDKLog: Response <#1386> <Error>:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
{
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x146f1600, state: FBSessionStateOpen, loginHandler: 0x146cca50, appID: 293072694193895, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x1468b170>, expirationDate: 2014-07-17 07:47:12 +0000, refreshDate: 2014-05-18 11:14:42 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n status,\n permission\n)>";
"com.facebook.sdk:HTTPStatusCode" = 400;
"com.facebook.sdk:ParsedJSONResponseKey" = (
{
body = {
error = {
code = 606;
message = "(#606) The global ID 100003190599973 is not allowed. Please use the application specific ID instead.";
type = OAuthException;
};
};
code = 400;
}
);
}
here I used the code for retrieving the the required information
NSString *query = [NSString stringWithFormat:#"select name, pic_square from user where uid = %#", curId];
NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql" parameters:queryParam HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
{
[namePicArray addObject:result[#"data"]];
}
}];
Thanks in advance.