user1960169 user1960169 - 5 months ago 20
iOS Question

NSURL(string: fullURL) returns error

Hello I am passing some data to webservice. This is my url

http://www.website.com/mobileapp/user.php?reg_device_id=566&alert_details=[{\n \"is_active\" = 1;\n \"term_id\" = 55;\n}, {\n \"is_active\" = 1;\n \"term_id\" = 2;\n}, {\n \"is_active\" = 1;\n \"term_id\" = 111;\n}, {\n \"is_active\" = 0;\n \"term_id\" = 21;\n}, {\n \"is_active\" = 0;\n \"term_id\" = 28;\n}, {\n \"is_active\" = 0;\n \"term_id\" = 1;\n}, {\n \"is_active\" = 0;\n \"term_id\" = 5;\n}, {\n \"is_active\" = 0;\n \"term_id\" = 4;\n}]


This is my webservice calling methid

for i in 0..<dm.array.count {
let id=dm.SettingsItems[i]["term_id"] as! String
var is_active="0"

if dm.array[i]
{
is_active="1"
}

let catRegDict:NSDictionary=["term_id":"\(id)","is_active":"\(is_active)"]
self.registerAyrray.append(catRegDict)
print("------REGISTER ARRAY------\(self.registerAyrray)")
}
let urlPath = "http://www.website.com/mobileapp/user.php?"
let path="reg_device_id=\(dm.DeviceID)&alert_details=\(self.registerAyrray)"

let fullURL = "\(urlPath)\(path)"
print(fullURL)


guard let endpoint = NSURL(string: fullURL) else {
print("Error creating endpoint")
return
}

let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request,completionHandler: { (data, response, error) in
do {


But seems this condition not satisfying. I can see its prenting this error message.

guard let endpoint = NSURL(string: fullURL) else {
print("Error creating endpoint")
return
}


But when I put the above url in browser its giving me the service response.What is the reason for this? Please help me.
Thanks

Answer

Try to encode you url and then create NSURL object like this.

let url = (fullURL as! NSString).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

Now pass this url in NSURL initialization.

Hope this will help you.

Comments