此扩展方法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];
网址的示例是:
此imageSize()
方法的作用是解析网址中的图片大小。上面的网址的尺寸为675x900-> widthxheight。
在极少数情况下,我们会遇到一个网址,其中没有大小信息,并且该网址不是上述格式。因此,如果找不到大小,则返回CGSize = (0 , 0)
。
我已经在所有预期的情况下测试了此方法。 但是由于某些原因,该方法导致崩溃。可能是我错过/弄乱了什么。
这是Crashlytics issue的链接。
任何帮助将不胜感激。
答案 0 :(得分:1)
崩溃很可能是由于强制展开可选项引起的。您的代码在多种情况下会使用它,如果URL中的文件名格式与预期的格式不同,则会导致运行时错误。尝试
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 let split1 = split0.last?.split(separator: "-")
{
if let split2 = split1.first?.decomposedStringWithCanonicalMapping.split(separator: "x")
{
width = (split2.first?.decomposedStringWithCanonicalMapping.toInt()) ?? 0
if split2.count > 1 {
height = (split2.last?.decomposedStringWithCanonicalMapping.toInt()) ?? 0
}
}
}
return CGSize(width: width, height: height)
}
答案 1 :(得分:1)
请不要使用强行解包!
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))
也请尝试使用卫兵let并在出现问题时返回nil。例如可以更改网址架构