gpt4 book ai didi

ios - 崩溃专门的 String.imageSize(),

转载 作者:行者123 更新时间:2023-11-28 11:37:56 24 4
gpt4 key购买 nike

我在 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 的例子是:

https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2019-02-07/675x900-1_-CdC62Y2hcV7208.jpg

https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2019-02-07/675x900-1_-697e3no8ec2E1I.jpg

https://s3-eu-west-1.amazonaws.com/mimg.haraj.com.sa/userfiles30/2019-02-07/675x900-1_-8Af5D20wh9b62z.jpg

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com