- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 String
的这个扩展方法中崩溃了:
func imageSize() -> CGSize {
// self = "https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2018-8-6/524x334-1_-E7VSb5T20mOouX.jpg"
var width = 0
var height = 0
let split0 = self.split(separator: "/")
if split0.count > 0 {
let split1 = split0.last?.split(separator: "-")
if (split1?.count)! > 0 {
let split2 = split1?.first?.decomposedStringWithCanonicalMapping.split(separator: "x")
width = (split2?.first?.decomposedStringWithCanonicalMapping.toInt())!
if (split2?.count)! > 1 {
// let split2 = split1![1].decomposedStringWithCanonicalMapping.split(separator: "-")
height = (split2?.last?.decomposedStringWithCanonicalMapping.toInt())!
}
}
}
return CGSize(width: width, height: height)
}
崩溃在线 return CGSize(width: width, height: height)
我已经创建了一个像这样的 NSString
版本来使用上面相同的方法:
@objc extension NSString {
func imageSize1() -> CGSize {
return (self as String).imageSize()
}
}
然后从 obj-c 代码中调用:
CGSize imageSize = [url imageSize1];
url 的例子是:
imageSize()
方法的作用是解析来自 url 的图像大小。上面的 url 包含尺寸 675x900 -> widthxheight。
在极少数情况下,我们会遇到一个没有大小信息的 url,而且 url 的格式也不是上面的格式。因此,如果未找到大小,则返回 CGSize = (0 , 0)
。
我已经在所有预期场景中测试了此方法。但由于某些原因,该方法导致崩溃。可能是我错过/弄乱了什么。
这是 Crashlytics 的链接 issue .
如有任何帮助,我们将不胜感激。
最佳答案
尽量不要使用强制解包!
let exampleString1 = "https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2018-8-6/524x334-1_-E7VSb5T20mOouX.jpg"
let exampleString2 = "https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2019-02-07/675x900-1_-697e3no8ec2E1I.jpg"
let exampleString3 = "https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2019-02-07/675x900-1_-CdC62Y2hcV7208.jpg"
extension String {
func imageSize() -> CGSize? {
// last url component
guard let imageName = self.split(separator: "/").last else { return nil }
guard let imageSizeString = imageName.split(separator: "-").first else { return nil }
let sizes = imageSizeString.split(separator: "x")
guard let first = sizes.first,
let last = sizes.last,
let wight = Int(String(first)),
let height = Int(String(last))
else { return nil }
return CGSize(width: wight, height: height)
}
}
exampleString1.imageSize() // Optional((524.0, 334.0))
exampleString2.imageSize() // Optional((675.0, 900.0))
exampleString3.imageSize() // Optional((675.0, 900.0))
同时尝试使用 guard let 并在出现问题时返回 nil。例如,可以更改 Url 架构
关于ios - 崩溃专门的 String.imageSize(),,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570085/
我有一个带有模板函数的基类,该函数具有通用模板类型和专用版本。 #ifndef BASE_CLASS #define BASE_CLASS #include using namespace std;
我有这个 3D vector 模板 template class Vec3TYPE{ public: union{ struct{ TYPE x,y,z; }; struct{ TY
我是一名优秀的程序员,十分优秀!